How to initialize const member variable in a class?

C++Constants

C++ Problem Overview


#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?

C++ Solutions


Solution 1 - C++

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.

Bjarne Stroustrup's explanation sums it up briefly: > A 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.

Solution 2 - C++

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
}

Solution 3 - C++

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 };

Solution 4 - C++

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){}

Solution 5 - C++

  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 )
     {
     }
    

Solution 6 - C++

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.

Solution 7 - C++

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) {}
};

Solution 8 - C++

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.

Solution 9 - C++

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.

Solution 10 - C++

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.

Solution 11 - C++

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChaitanyaView Question on Stackoverflow
Solution 1 - C++Dinkar ThakurView Answer on Stackoverflow
Solution 2 - C++Fred LarsonView Answer on Stackoverflow
Solution 3 - C++ravs2627View Answer on Stackoverflow
Solution 4 - C++GANESH B KView Answer on Stackoverflow
Solution 5 - C++borisbnView Answer on Stackoverflow
Solution 6 - C++MuskyView Answer on Stackoverflow
Solution 7 - C++Viet Anh DoView Answer on Stackoverflow
Solution 8 - C++BaranView Answer on Stackoverflow
Solution 9 - C++Gambler AzizView Answer on Stackoverflow
Solution 10 - C++dhokar.wView Answer on Stackoverflow
Solution 11 - C++Molybdenum OxideView Answer on Stackoverflow