7

How do I define a non-static const data member of a class in C++? If I try compiling the following code:

class a
{
public:
    void print()
    {
        cout<<y<<endl;
    }
private:
    const int y=2;
};

int main()
{
    a obj;
    obj.print();
}

I get an error

ISO C++ forbids initialization of member ‘y’

3 Answers 3

26

In C++03 you can initialize const fields of a class using a member-initializer list in the constructor. For example:

class a
{
public:
    a();

    void print()
    {
        cout<<y<<endl;
    }

private:
    const int y;
};

a::a() : y(2)
{
    // Empty
}

Notice the syntax : y(2) after the constructor. This tells C++ to initialize the field y to have value 2. More generally, you can use this syntax to initialize arbitrary members of the class to whatever values you'd like them to have. If your class contains const data members or data members that are references, this is the only way to initialize them correctly.

Note that in C++11, this restriction is relaxed and it is fine to assign values to class members in the body of the class. In other words, if you wait a few years to compile your original code, it should compile just fine. :-)

2
  • So, will the space allocated to the variable y be in static block or in the normal variable stack.
    – Atishay
    Commented Jul 31, 2011 at 19:42
  • 2
    @Atishay- The space for y will be allocated wherever space for the object is allocated. If the object is allocated dynamically via new, it will be put in the heap. If the object is allocated automatically on the stack, it will be put in the stack. If the object is declared globally, it will be placed wherever global objects live. Commented Jul 31, 2011 at 19:43
6

Initialize it in the constructor initialization list.

class a
{
  const int y;
public:
  a() : y(2) { }
};
1
  • please,can you explain this,that what effect const will produce on 'y'?
    – nobalG
    Commented Jul 31, 2011 at 19:30
4

You can't use an initializer inside the class definition. You need to use the constructor initialization instead:

a::a() : y(2) {}
2
  • please,can you explain this,that what effect const will produce on 'y'?
    – nobalG
    Commented Jul 31, 2011 at 20:02
  • y will be constant in any code executed from the body of the constructor onwards. Commented Jul 31, 2011 at 20:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.