#include <iostream>
using namespace std;
class T1
{
const int t = 100;
public:
T1()
{
cout << "T1 constructor: " << t << endl;
}
};
When I am trying to initialize the const data member t with 100. But it’s giving me the following error:
test.cpp:21: error: ISO C++ forbids initialization of member ‘t’
test.cpp:21: error: making ‘t’ static
How can I initialize a const member?
The
constvariable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution.Bjarne Stroustrup’s explanation sums it up briefly:
A
constvariable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.Here the assignment
t = 100happens in initializer list, much before the class initilization occurs.