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?
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:
You would then use this as:
The sample code given by @einpoklum is not working as it is because of the missing initialization of the static member
foo_
, missing inheritance inFooHolder
declaration, and missingpublic
keywords since we are dealing with classes. Here is the fixed version of it.I know that this question has already been answered but I would like to provide a small example of inheritance with static members. This is a very nice way to demonstrate the usefulness as well as what is happening with the static variables and the respective constructors.
FooBase.h
FooBase.cpp
DerivedFoos.h
DerivedFoos.cpp
main.cpp
If
__FUNCTION__
is not working for you in your constructors then you can use something similar that can replace it such as__PRETTY_FUNCTION__
or__func__
, or manually type out each class's name:(
.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.
To ensure that each class has its own static variable, you should use the "Curiously recurring template pattern" (CRTP).
Alas, C++ has no virtual static data members. There are several ways to simulate this, more or less:
I suggest a different CRTP-based solution, using a mix-in class:
The only thing you need to do in a subclass is also indicate the mix-in inheritance. There might be some virtual inheritance caveats I'm missing here (as I rarely use it).
Note that you either have to instantiate and initialize each subclass' static variable somewhere, or you can make it an
inline
variable (C++17) and initialize it within the template.This answer was adapted from my answer to a dupe question.