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

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();

Leave a Comment