[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 I am trying to initialize the const member variable 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 value?

This question is related to c++ constants

The answer is


There are couple of ways to initialize the const members inside the class..

Definition of const member in general, needs initialization of the variable too..

1) Inside the class , if you want to initialize the const the syntax is like this

static const int a = 10; //at declaration

2) Second way can be

class A
{
  static const int a; //declaration
};

const int A::a = 10; //defining the static member outside the class

3) Well if you don't want to initialize at declaration, then the other way is to through constructor, the variable needs to be initialized in the initialization list(not in the body of the constructor). It has to be like this

class A
{
  const int b;
  A(int c) : b(c) {} //const member initialized in initialization list
};

If a member is a Array it will be a little bit complex than the normal is:

class C
{
    static const int ARRAY[10];
 public:
    C() {}
};
const unsigned int C::ARRAY[10] = {0,1,2,3,4,5,6,7,8,9};

or

int* a = new int[N];
// fill a

class C {
  const std::vector<int> v;
public:
  C():v(a, a+N) {}
};

This is the right way to do. You can try this code.

#include <iostream>

using namespace std;

class T1 {
    const int t;

    public:
        T1():t(100) {
            cout << "T1 constructor: " << t << endl;
        }
};

int main() {
    T1 obj;
    return 0;
}

if you are using C++10 Compiler or below then you can not initialize the cons member at the time of declaration. So here it is must to make constructor to initialise the const data member. It is also must to use initialiser list T1():t(100) to get memory at instant.


you can add static to make possible the initialization of this class member variable.

static const int i = 100;

However, this is not always a good practice to use inside class declaration, because all objects instacied from that class will shares the same static variable which is stored in internal memory outside of the scope memory of instantiated objects.


Another possible way are namespaces:

#include <iostream>

namespace mySpace {
   static const int T = 100; 
}

using namespace std;

class T1
{
   public:
   T1()
   {
       cout << "T1 constructor: " << mySpace::T << endl;
   }
};

The disadvantage is that other classes can also use the constants if they include the header file.


Another solution is

class T1
{
    enum
    {
        t = 100
    };

    public:
    T1();
};

So t is initialised to 100 and it cannot be changed and it is private.


In C++ you cannot initialize any variables directly while the declaration. For this we've to use the concept of constructors.
See this example:-

#include <iostream>

using namespace std;

class A
{
    public:
  const int x;  
  
  A():x(0) //initializing the value of x to 0
  {
      //constructor
  }
};

int main()
{
    A a; //creating object
   cout << "Value of x:- " <<a.x<<endl; 
   
   return 0;
}

Hope it would help you!


Well, you could make it static:

static const int t = 100;

or you could use a member initializer:

T1() : t(100)
{
    // Other constructor stuff here
}

  1. You can upgrade your compiler to support C++11 and your code would work perfectly.

  2. Use initialization list in constructor.

    T1() : t( 100 )
    {
    }
    

If you don't want to make the const data member in class static, You can initialize the const data member using the constructor of the class. For example:

class Example{
      const int x;
    public:
      Example(int n);
};

Example::Example(int n):x(n){
}

if there are multiple const data members in class you can use the following syntax to initialize the members:

Example::Example(int n, int z):x(n),someOtherConstVariable(z){}