class base { public: base a; };
It gives compilation error.
class base { public: static base a; };
whereas this code does not give compilation error
Since, static function does not know about object, so, it is impossible for a static function to know on which class object or class instance it is being called. Hence, whenever, we try to call non-static variable from a static function, the compiler flashes an error.
static members are accessed by their class name which encapsulates them, but non-static members are accessed by object reference. static members can't use non-static methods without instantiating an object, but non-static members can use static members directly.
Static class can't contain non-static members because by definition it can't be instantiated so there's no possibility to use these members.
We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class.
Because static
class members are not stored in the class instance, that's why a static
would work.
Storing an object inside another object of the same type would break the runtime - infinite size, right?
What would sizeof
return? The size of the object needs to be known by the compiler, but since it contains an object of the same type, it doesn't make sense.
I'm guessing the error is something like
field ‘a’ has incomplete type
This is because when not static, the class A
is not fully defined until the closing brace. Static member variables, on the other hand, need a separate definition step after the class is fully defined, which is why they work.
Search for the difference between declaration and definition for more thorough explanations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With