c++ - How to initialize const member variable in a class? -
#include <iostream> using namespace std; class t1 { const int t = 100; public: t1() { cout << "t1 constructor: " << t << endl; } };
when trying initialize const member variable t
100. it's giving me following error:
test.cpp:21: error: iso c++ forbids initialization of member ‘t’ test.cpp:21: error: making ‘t’ static
how can initialize const
value?
the const
variable specifies whether variable modifiable or not. constant value assigned used each time variable referenced. value assigned cannot modified during program execution.
bjarne stroustrup's explanation sums briefly:
a class typically declared in header file , header file typically included many translation units. however, avoid complicated linker rules, c++ requires every object has unique definition. rule broken if c++ allowed in-class definition of entities needed stored in memory objects.
a const
variable has declared within class, cannot defined in it. need define const variable outside class.
t1() : t( 100 ){}
here assignment t = 100
happens in initializer list, before class initilization occurs.
Comments
Post a Comment