Chaitanya
Chaitanya

Reputation: 3469

How do I initialize a const data member?

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

Upvotes: 154

Views: 425125

Answers (13)

Minh Tran
Minh Tran

Reputation: 510

How the const member is initialized depends on whether the member is static or non-static. If the member is static, the const member is an immutable value shared by all class instances.

If the member is non-static, the const member is immutable, but may vary with every instantiation. In the example below, member3, member4 are constant but different for each instance. member5 is reinitialized in A's initializer list.

#include <iostream>

int GetRandomNum()
{
    int retVal;
    std::cout << "Enter a number to initialize A: "; 
    std::cin >> retVal; 
    return retVal; 
}

struct A
{
    static const int member1 = 1;
    static const int member2;

    const int member3 = GetRandomNum(); // Dynamically assigned
    const int member4; // Uninitialized, dynamically assigned
    const int member5 = 0; // Literal
    const int member6 = 6;

    A() : member4(GetRandomNum()), member5(5) // member5 is redefined!
    {
    }

    void PrintMember1() { std::cout << "member1: " << member1 << "\n"; }
    void PrintMember2() { std::cout << "member2: " << member2 << "\n"; }
    void PrintMember3() { std::cout << "member3: " << member3 << "\n"; }
    void PrintMember4() { std::cout << "member4: " << member4 << "\n"; }
    void PrintMember5() { std::cout << "member5: " << member5 << "\n"; }
    void PrintMember6() { std::cout << "member6: " << member6 << "\n"; }
};

const int A::member2 = 2; 

int main()
{
    // Do twice. 
    for (int i = 1; i <= 2; i++)
    {
        A a1;
        a1.PrintMember1();
        a1.PrintMember2();
        a1.PrintMember3();
        a1.PrintMember4();
        a1.PrintMember5();
        a1.PrintMember6();
    }
    
    cout << "Exiting ...\n";
    return 0;
}

Input/Output:

Enter a number to initialize A: 100
Enter a number to initialize A: 200
member1: 1
member2: 2
member3: 100
member4: 200
member5: 5
member6: 6
Enter a number to initialize A: 300
Enter a number to initialize A: 400
member1: 1
member2: 2
member3: 300
member4: 400
member5: 5
member6: 6

Upvotes: 0

MolyOxide
MolyOxide

Reputation: 79

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! Please do Upvote 😉

Upvotes: 1

Ingo
Ingo

Reputation: 736

In 2023 your example compiles now without any errors. There is no need to use an initialization list or to make the variable static. I compiled and run your identical code with:

g++ -std=c++11 -Wall -Wpedantic -Wextra -Werror -Wuninitialized -Wsuggest-override test.cpp

I use:

~$ g++ --version
g++ (Debian 10.2.1-6) 10.2.1 20210110
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 0

Gambler Aziz
Gambler Aziz

Reputation: 41

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.

Upvotes: 1

Dinkar Thakur
Dinkar Thakur

Reputation: 3103

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.

Upvotes: 157

GANESH B K
GANESH B K

Reputation: 431

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

Upvotes: 27

dhokar.w
dhokar.w

Reputation: 470

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.

Upvotes: 0

ravs2627
ravs2627

Reputation: 861

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

Upvotes: 44

Viet Anh Do
Viet Anh Do

Reputation: 489

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

Upvotes: 3

Baran
Baran

Reputation: 31

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.

Upvotes: 2

Musky
Musky

Reputation: 91

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.

Upvotes: 9

borisbn
borisbn

Reputation: 5054

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

Upvotes: 14

Fred Larson
Fred Larson

Reputation: 62073

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
}

Upvotes: 65

Related Questions