Chaitanya Chaitanya - 1 year ago 171
C++ Question

how to initialize const member variable in a class C++

#include <iostream>

using namespace std;
class T1
const int t = 100;


cout << "T1 constructor: " << t << endl;

When I am trying to initialize the const member variable
with 100. Its giving error like

test.cpp:21: error: ISO C++ forbids initialization of member ‘t’
test.cpp:21: error: making ‘t’ static

How to initialize one ?

Answer Source

The const variable 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.

class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

A const variable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.

T1() : t( 100 ){}

Here the assignment t = 100 happens in initializer list, much before the class initilization occurs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download