Bitdiot
Bitdiot

Reputation: 1598

How to create a member variable between instance and static scope?

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!

Upvotes: 1

Views: 1545

Answers (2)

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

If I understand correctly you want a variabile which is "static" among all instances of the same class, but which varies among different classes even if one is derived from the other.

The solution would be to define a function on the base class, which returns the value of a static variable as in the following:

class Base  {
    int &static_var() {
       static int myvar = 42;
       return myvar;
    }
};

class Derived: public Base {
    int &static_var() {
       static int myvar = 17;
       return myvar;
    }
};

This way you should have:

Base b;
b.static_var(); // should be 42
Derived c;
c.static_var(); // should be 17

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168646

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.

class A {
  public: static Configurator config;
};
class P {
  public: static Configurator config;
};
class B : public A {};
class C : public A {};
class Q : public P {};
class R : public P {};

A less obvious way is to use CRTP.

template <class Derived> class Configurator {
  public: static int configValue;
};
class A : public Configurator<A> {};
class B : public A {};
class P : public COnfigurator<P> {};
class Q : public P {};

Upvotes: 2

Related Questions