Search code examples
c++inheritancestaticinitializationglobal

Initialize static member of class which is itself a class in subclass


I have two classes of which one is a subclass of the other. The classes are layed out as a singleton. So the base class contains a static member which is set to the only instance of that class and can be refered to by a getter function (not relevant here, so I left it out). I now want to create the subclass in global context and save the instance to the static member variable. This is essentially what I have:

class LightBase
{
    protected:
        static LightBase instance_;
    // .. stuff
}

class NormalLight0_5 : public LightBase
{
    //.. other stuff
}

class NormalLight1_0 : public LightBase
{
    //.. other stuff
}

#ifdef CONFIG_LIGHT_TYPE_NORMAL0_5
NormalLight0_5 LightBase::instance_();  // <-- my attempt to instantiate a light of type 0.5
#elif
NormalLight1_0 LightBase::instance_();  // <-- my attempt to instantiate a light of type 1.0
#endif

But I get the following error:

error: no declaration matches 'NormalLight1_0 LightBase::instance_()'

What is the cause of this?


Solution

  • You need pointers or references for polymorphism. A LightBase member can only store a LightBase not one of its subclasses. Hence, it is not really the definition that is the problem, but rather your declaration is already off. In any case the definition must match the declaration.

    You can use a std::unique_ptr:

    #include <memory>
    
    class LightBase {
        protected:
            static std::unique_ptr<LightBase> instance_;
    };
    
    class NormalLight1_0 : public LightBase {};
    
    std::unique_ptr<LightBase> LightBase::instance_ = std::make_unique<NormalLight1_0>();