hims15
hims15

Reputation: 96

why you can not initialize the variable inside the class in c++

i know that you can not initialize the member variable(other than static const) inside the class directly without using constructor.

but just wanted to know what is the reason behind this. below is the code snippet

if any body could help

class a 
{

    int c=5;

// giving error error C2864: 'a::c' : only static const integral data members can be 

// initialized within a class

    int b;


public:
    a():c(1),b(2){}

    void h()
    {
        printf("%d,%d",c,b);
    }
};

int main()
{

    a l;

    l.h();

    getchar();
}

Upvotes: 4

Views: 3186

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

Actually you can. But only in C++11.

The following is a valid C++11 code:

class A
{
    int x = 100; //valid in c++11
};

Your compiler might not support this, but GCC 4.8.0 compiles it fine.

Hope that helps.

Upvotes: 5

maditya
maditya

Reputation: 8896

The class definition is mainly meant to tell other classes what interface your class will have and how much memory it occupies, as well as any values associated with the class that are already known at compile time (i.e. constants). There is no executable code directly in the class definition (although there will probably be executable code in a function that's defined within the class's definition). The code that will execute lies in the definitions of the functions themselves.

Edit: Apparently this is supported in C++11.

Upvotes: 1

Related Questions