27
class base {
public:
    base a;
};

It gives compilation error.

class base {
public:
    static base a;
};

whereas this code does not give compilation error

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
user966379
  • 2,823
  • 3
  • 24
  • 30

2 Answers2

42

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
6

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621