I have a base class A with a constant static variable a. I need that instances of class B have a different value for the static variable a. How could this be achieved, preferably with static initialization ?
class A {
public:
static const int a;
};
const int A::a = 1;
class B : public A {
// ???
// How to set *a* to a value specific to instances of class B ?
};
May be we can try this way as below :: The benefit of the below is that you don't have to write the code multiple times, but the actual generated code might be big.
This is part of my other code example .. don't mind many other data but concept can be seen.
You can't. There is one instance of the static variable that is shared by all derived classes.
You can do this with Curiously recurring template pattern (you'll have to lose the
const
though).Static members are unique in the application. There is a single
A::a
constant in your system. What you can do is create aB::a
static constant inB
that will hide theA::a
static (if you don't use the fully qualified name: