I have a class and want to create a const int variable but the value for the variable is not available to me in constructor of the class.
In initialization method of the
You cannot do that, because you cannot change the value of a const variable. by the time initClassA
runs the const data member has already been initialized (to some garbage value in this case). So you can only really initialize the data member to some value in the constructor initializer list.
If you want to set the variable only once, then you can make is non-const, and add a guard so it can only be set once. This isn't pretty but it would work:
class A
{
private :
long int iValue;
bool isInitialised;
public :
A() : iValue(0), isInitialized(false);
bool initClassA() {
if (isInitialized) return false;
iValue = something:
isInitialized = true;
return true;
}
}
But it isn't good practice to have objects that can be initialized or not. Objects should be in a coherent state when constructed, and clients should not have to check whether these objects are initialized.