Say that I have a C++ class with some fields with static storage duration, call it class A.

Is there some way to use inheritance to "inject" these static fields into classes which derive from class A? That is to say, if class B and class C derive from A, B and C will have the same static fields as the base class A, shared with all other instances of B and C, but operations on these fields within instances of B and C will be distinct to their respective subclasses, and not affect each other.

1 Answer 1


No, and from the theoretical view of how inheritance works, it wouldn't make sense.

However, if you are using inheritance only for implementation purposes, templating the base class on the derived class would make that work, but then the various classes no longer share a common ancestor.

template <typename Derived>
class A { protected: static int count; };
class B : private A<B> { public: B() { ++count; } };
class C : private A<C> { public: C() { ++count; } };
  • Thanks, it looks like something that should work for my code. It's OK that they don't share a common ancestor as for what I have in mind, it won't be necessary to reference the sub-classes polymorphically through say a pointer-to-base.
    – MattyZ
    Jan 5, 2017 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.