Question

Is there a way of initializing a static sub-object of a class after main() has started ?

Was it helpful?

Solution

One way to do that is to replace the static member data which static member function.

Say you've this class:

class A
{
   static B static_b; //static member data
};

//.cpp
B A::static_b; //definition (required)

So instead of that you can define your class as:

class A
{
   static B static_b()  //static member function!
   {
       static B b;
       return b;
   }
};

Note that it is not thread-safe, but you can make it thread-safe as well.

OTHER TIPS

You can use a pointer for this object:

class SomeClass{
public:
    static SomeOtherClass* p;
};

SomeOtherClass* SomeClass::p;    

void main(){
    SomeClass::p = new SomeOtherClass();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top