Reputation: 95
Consider the following code:
#include <iostream >
using namespace std;
class A
{
private:
int x;
public:
A(int _x) { x = _x; }
int get() { return x; }
};
class B
{
static A a;
public:
static int get()
{ return a.get(); }
};
A B::a(0);
int main(void)
{
B b;
cout << b.get();
return 0;
}
My book says:
If we do not use the line of code A B::a(0)
,there is a compiler error because static member a is not defined in B. To fix the error, we need to explicitly define a
.
However, I thought of initializing object a
as static A a(0);
but it gives me a compiler error. Can someone explain why I can't initialize object a in the manner I described, and why it is necessary to initialize it as they had given it in book.
Upvotes: 1
Views: 79
Reputation: 117298
If you want to define a
inline, you need to inline
it, which is possible from C++17:
class B {
inline static A a{0}; // or inline static A a = 0;
public:
static int get() { return a.get(); }
};
Upvotes: 1