+ 26

Is there any other way around to assign a value after creating a constant variable?

As a thumb rule it's being said that constant variables must be initialized at the time of declaring a constant variable.

18th Aug 2018, 5:36 AM
Byk
10 Respostas
+ 5
If the constant is a member of a class you can initialize it using constructor initializer, otherwise I don't think it was feasible. https://www.sololearn.com/learn/CPlusPlus/1896/
18th Aug 2018, 6:31 AM
Ipang
+ 5
const specifies that the variable is unmodifiable during execution time, so no you can't change its content once it defined. Since you are looking for the non-static data members initialization, the following one would be one possible solution: // class declaration class A { public: A(); private: const int K; }; // class definition A::A() : K(1000) { }
18th Aug 2018, 7:09 AM
Babak
Babak - avatar
+ 3
You can use const_cast any time like: class A { public: A() : _var(0) {} void f() { const_cast<int&>(_var) = 100; } private: const int _var; }; BUT it is wierd design!
19th Aug 2018, 7:45 AM
NoOmega73
NoOmega73 - avatar
0
in Java not possible
25th Aug 2018, 12:21 PM
Coder🇼🇳 #21
- 1
Just imagine that compiler is allowed to place the constant value itself instead loading it from the variable any time it is used. It means that constant variable couldn't exist in the binary.
19th Aug 2018, 3:49 PM
Sergey Ushakov
Sergey Ushakov - avatar
- 1
no
21st Aug 2018, 3:33 PM
Coder🇼🇳 #21
- 2
Oi
28th Aug 2018, 11:45 AM
Davi Lopes
Davi Lopes - avatar
- 2
OlĂĄ
28th Aug 2018, 11:45 AM
Davi Lopes
Davi Lopes - avatar
- 3
you can use a setter metode
20th Aug 2018, 9:02 AM
bruno villalobos
bruno villalobos - avatar
- 3
#include<iostream> using name spece std; int main() { int a,b; int sum; count<<"Enter anumber\n; cin>>a; cout<<"Enter another number\n; cin>> b;sum is:"<<sum<<endl return 0;
27th Aug 2018, 8:58 AM
Slavik Gorbunov
Slavik Gorbunov - avatar