BetaCoder
BetaCoder

Reputation: 75

Why I cannot declare an static member of a class with only a forward declaration c++?

Why can't I declare an static member inside a class without providing the full definition (include)?

I know forward declarations only can be used if the members of the class are not really used, like declaring a pointer or a reference because the compiler must know the size of the type and all pointers or references are the same size. But why I can't declare an static member this way? I mean the variable will not life inside any instance of the class, it won't add up to the object's size neither it's lifetime, it will be initialized the first time is used. Declaring an static member is only for programmers, just gives the name (i.e: Type::static_var for example) and access modifiers, but it will live in the .text section of the program, as all global variables.

In code: A.h


class B;

class A
{
    static B b;
    //other stuff
}

B.h

class B
{
    C c;
    D d;
}

A.cpp

B A::b;
///whatever more
A::A(){}
///...

And in other place will be something like:

class D : A{/*...*/};
class C : A{/*...*/};

I know I could fix this really easy just doing #include "B.h" but I can't because my B struct has a bunch of objects whom inherit from A and that would result in circular inclusion. I just want a list of every object whom inherit from A to be accessed from every object whom inherit from A (I know it sounds messy but it makes sense in our project and everything is resolved at compile time). We're currently doing it with pointers, an setting it up in main, but I want it to life inside A, not the global namespace.

Upvotes: 0

Views: 548

Answers (1)

eerorika
eerorika

Reputation: 238461

Why can't I declare an static member inside a class without providing the full definition

You can. It is allowed by the language as long as the declaration is not a definition. The declaration of the static member in your example is not a definition, so there is no problem.

The problem in your program is that you failed to define B before you define the static member variable in A.cpp. Following simplified program is well-formed:

class B;

class A
{
    static B b; // B is incomplete; this declaration is fine
};

class B{};      // B is now complete

B A::b;         // The variable can be defined, because B is complete

it will be initialized the first time is used.

No; That's not how static members work. They are initialised during program startup in static initialisation phase just like namespace variables with static storage.

Upvotes: 3

Related Questions