How do I define a non-static const data member of a class in C++? If I try compiling the following code:
class a
{
public:
void print()
{
cout<<y<<endl;
}
private:
const int y=2;
};
int main()
{
a obj;
obj.print();
}
I get an error
ISO C++ forbids initialization of member ‘y’
In C++03 you can initialize const
fields of a class using a member-initializer list in the constructor. For example:
class a
{
public:
a();
void print()
{
cout<<y<<endl;
}
private:
const int y;
};
a::a() : y(2)
{
// Empty
}
Notice the syntax : y(2)
after the constructor. This tells C++ to initialize the field y
to have value 2. More generally, you can use this syntax to initialize arbitrary members of the class to whatever values you'd like them to have. If your class contains const
data members or data members that are references, this is the only way to initialize them correctly.
Note that in C++11, this restriction is relaxed and it is fine to assign values to class members in the body of the class. In other words, if you wait a few years to compile your original code, it should compile just fine. :-)
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