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

Solution 1:

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

Solution 2:

To ensure that each class has its own static variable, you should use the "Curiously recurring template pattern" (CRTP).

template <typename T>
class Base
{
    static int staticVar;
};

template <typename T> int Base<T>::staticVar(0);

class DerivedA : public Base<DerivedA> {};
class DerivedB : public Base<DerivedB> {};

Solution 3:

They will share the same instance.

You'll need to declare separate static variables for each subclass, or you could consider a simple static map in which you could store variables that are referenced by derived classes.


Edit: A possible solution to this would be to define your base class as a template. Having a static variable defined in this template would mean that each derived class will have it's own instance of the static.

Solution 4:

There is only one staticVar in your case: Base::staticVar

When you declare a static variable in a class, the variable is declared for that class alone. In your case, DerivedA can't even see staticVar (since it's private, not protected or public), so it doesn't even know there is a staticVar variable in existence.