I got a newbie C++ question, sorry about this…
In C++ if I have instance variables in a base class, all derived instances get their own personal copy of the base instance variable.
Now, if I have a class variable of the bass class (a static member), then all derived instances can share the base’ class variable.
I’d like to be able to create a base variable that is instantiated per instance of derived class but not by instances of derived classes of these derived classes.
Is this possible? How do I do so? Or what’s the best way (workaround) to do such a thing?
So to give a (bad) example:
Suppose I have class A and it has derived classes B, C, and D.
I also have class P and it has derived classes Q,R,S.
Now, I have a Configurator class. And it has many fancy functions that rely on instance variables of Configurator class. I like A and P to derive from a Configurator class, which stores a separate configurations for A and P. That way B,C,D have share a common configurations while Q,R,S share their own, separate, configuration.
But, Configurator class will create separate instances of configurations for B,C,D, and Q,R,S, because of the way it is written.
So, anyways, it would be nice to have Configurator class contain member variables that are instantiated by derived class instead of per instance.
thanks!
The obvious way would be to use composition, not inheritance. This way, each of A and P have their own static configuration, shared among their respective derived classes.
A less obvious way is to use CRTP.