Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non static const data members

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’
like image 322
Atishay Avatar asked Jul 31 '11 19:07

Atishay


1 Answers

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. :-)

like image 76
templatetypedef Avatar answered Oct 10 '22 12:10

templatetypedef