Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a class allowed to have a static member of itself, but not a non-static member?

class base { public:     base a; }; 

It gives compilation error.

class base { public:     static base a; }; 

whereas this code does not give compilation error

like image 820
user966379 Avatar asked Dec 15 '11 09:12

user966379


People also ask

Why can't static member function access a non static member of a class?

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.

How is a static member different from non static member of a class?

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.

Can we declare non static members in static class?

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.

Can a class have a static member?

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.


2 Answers

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.

like image 200
Luchian Grigore Avatar answered Oct 20 '22 17:10

Luchian Grigore


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.

like image 27
Some programmer dude Avatar answered Oct 20 '22 17:10

Some programmer dude