Why can't I initialise static variables in initializer list?
c++, oop, static
Solution
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);
}
Problem
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?