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 class i get the value. Can I assign it in that method? As I am assigning it only once (as const says) why it isn't working?
Code is as Following [Just a ProtoType] :
File : A.h
Class A
{
private :
const long int iConstValue;
public :
A();
initClassA();
}
File : A.cpp
A::A()
{
//CanNot initialize iConstValue (Don't have it)
}
A::initClassA(some params)
{
// calculation according to params for iConstValue
iConstValue = (some value)
}
This is not working. Somebody has any Solutions?
NOTE : I Can not get value for iconstValue in constructor by any way as there are some restriction. So Please don't suggest to do that.
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.
Const member variables must be initialized. A member initialization list can also be used to initialize members that are classes. When variable b is constructed, the B(int) constructor is called with value 5. Before the body of the constructor executes, m_a is initialized, calling the A(int) constructor with value 4.
A small example:
class A
{
public:
A():a(initial_value_of_a()) {}
private:
const int a;
int initial_value_of_a() { return 5; /* some computation here */ };
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With