Search code examples
c++inheritancestatic

Are static variables in a base class shared by all derived classes?


If I have something like

class Base {
    static int staticVar;
}

class DerivedA : public Base {}
class DerivedB : public Base {}

Will both DerivedA and DerivedB share the same staticVar or will they each get their own?

If I wanted them to each have their own, what would you recommend I do?


Solution

  • They will each share the same instance of staticVar.

    In order for each derived class to get their own static variable, you'll need to declare another static variable with a different name.

    You could then use a virtual pair of functions in your base class to get and set the value of the variable, and override that pair in each of your derived classes to get and set the "local" static variable for that class. Alternatively you could use a single function that returns a reference:

    class Base {
        static int staticVarInst;
    public:
        virtual int &staticVar() { return staticVarInst; }
    }
    class Derived: public Base {
        static int derivedStaticVarInst;
    public:
        virtual int &staticVar() { return derivedStaticVarInst; }
    }
    

    You would then use this as:

    staticVar() = 5;
    cout << staticVar();