banarun
banarun

Reputation: 2321

Why can't I initialise static variables in initializer list?

I was trying to use the following code:

class Test 
{
private:
    static int x;
public:
    Test(int i) : x(i) {}
};
main()
{
    Test a(5);
}

But, then I got the error:

‘int Test::x’ is a static data member; it can only be initialized at its definition

What is wrong with the above implementation?

Upvotes: 3

Views: 2823

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490623

The error message is telling you the problem pretty accurately.

The problem is that a static member has only one instance, regardless of how many instances of the class you happen to create. You only initialize it once, even if you create multiple instances of the class -- which means it can't be attached to the constructor.

class Test 
{
private:
    static int x;
public:

};

int Test::x = 1; // newly added

main()
{
    Test a;
}

In this case, it looks like you may not really want a static member variable at all though -- you're passing a value to initialize it when you create an instance of the class, which tends to indicate that you may just want a normal member variable:

class Test 
{
private:
    int x;
public:
    Test(int i) : x(i) {}
};

main()
{
    Test a(5);
}

In this case, if you wanted a second instance of the object with a different value, you could do that:

main() { 
    Test a(5), b(1);
}

Upvotes: 4

John Zwinck
John Zwinck

Reputation: 249582

Class static variables must have storage, and may have initialization, outside the class body. Like this:

class Test 
{
private:
    static int x;
public:
    Test(int i) { x = i; }
};
int Test::x = 42;

main()
{
    Test a(5);
}

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308520

Static variables aren't part of the object - they're part of the class. That's why you can't initialize them along with the other members of the object.

Somewhere in a source file you need to provide a definition of the static variable, and you can put its initialization there:

int Test::x = 5;

Upvotes: 3

Related Questions