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

Viewed 57146

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?

7 Answers

The sample code given by @einpoklum is not working as it is because of the missing initialization of the static member foo_, missing inheritance in FooHolder declaration, and missing public keywords since we are dealing with classes. Here is the fixed version of it.

#include <iostream>
#include <string>

class A {
public:
    virtual const int& Foo() const = 0;
};

template <typename T>
class FooHolder : public virtual A {
public:
    const int& Foo() const override { return foo_; }
    static int foo_;
};

class B : public virtual A, public FooHolder<B> { };
class C : public virtual A, public FooHolder<C> { };

template<>
int FooHolder<B>::foo_(0);
template<>
int FooHolder<C>::foo_(0);

int main()
{
  B b;
  C c;
  std::cout << b.Foo() << std::endl;
  std::cout << c.Foo() << std::endl;
}
Related