Non-static members are instance dependent. They are initialized when a valid instance is initialized.
The problem with your example is that, it tries to access a non-static member through the class interface without first initializing a concrete instance. This is not valid.
You can either make it static
:
class C{
public:
static int age;
};
which requires you to also define age
before using at runtime by: int C::age = 0
. Note that value of C::age
can be changed at runtime if you use this method.
Or, you can make it const static
and directly initialize it like:
class C{
public:
const static int age = 0;
};
In this case, value of C::age
is const
.
Both of which will let you get it without an instance: C::age
.