I have these C++ classes:
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base
{
};
class B : public Base
{
};
Will the x static variable be shared among A and B, or will each one of them have it’s own independent x variable (which is what I want)?
There will only be one instance of
xin the entire program. A nice work-around is to use the CRTP:This will create a different
Base<T>, and therefore a distinctx, for each class that derives from it.You may also need a “Baser” base to retain polymorphism, as Neil and Akanksh point out.