Search code examples
c++staticprivateabstract

How to use private static member variable of abstract type


I am trying to declare a private static member variable of an abstract type. The code:

class AbstractClass{
public:
    virtual double operator()() = 0;
};

class ThisOneContainsIt{
private:
    static AbstractClass var; //this does not work
    static AbstractClass & var; //this seems to work, but...
}

//my .cpp
AbstractClass & ThisOneContainsIt::var; //...this does not work either

Now I ran out of ideas. I am pretty sure this must be somehow possible - I could always delete the = 0 to make the class non-abstract, but that's not what I really want to do.


Solution

  • You can't instantiate an abstract class. You have to derive a class from it and override the pure virtual methods. You can then instantiate that derived class, and use the created instance to initialize your abstract class reference :

    class AbstractClass
    {
        public:
            virtual double operator()() = 0;
    };
    
    class DerivedClass : public AbstractClass
    {
        public:
            double operator()() override { return 0.0; }
    };
    
    class ThisOneContainsIt
    {
        private:
            static DerivedClass d;
    
            static AbstractClass &var;
    };
    
    DerivedClass ThisOneContainsIt::d; 
    
    AbstractClass &ThisOneContainsIt::var(d);
    

    I don't know why you would want to do something like that, though. You might as well do it like this :

    class ThisOneContainsIt
    {
        private:
            static DerivedClass var;
    };
    
    DerivedClass ThisOneContainsIt::var;