+ 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.
10 Answers
+ 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/
+ 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) { }
+ 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!
0
in Java not possible
- 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.
- 1
no
- 2
Oi
- 2
OlĆ”
- 3
you can use a setter metode
- 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;