I have these C++ classes:
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base
If you are making X as static then it will be shared among all the child classes. No issues with the function being static.
The former. Local static variables are bound to the method containing them, and method
exists in one incarnation for all subclasses (in fact, for the whole app, even though the rest of the program does not see the method).
I am pretty sure it will be shared between A and B.
If you want independent variables you can use the "Curiously Recurring Template Pattern" like:
template<typename Derived>
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base<A>
{
};
class B : public Base<B>
{
};
Of course if you want polymorphism, you would have to define a even "Baser" class which Base derives from, as Base<A>
is different from Base<B>
like:
class Baser
{
};
template<typename Derived>
class Base : public Baser
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base<A>
{};
class B : public Base<B>
{};
Now A and B can also be polymorphic.
The variable will be shared - it is per-function - in this case the function it belongs to is Base::method()
. However if class Base
was a template class you would get one instance of the variable for each instantiation (each unique set of actual template parameters) of class Base
template - each instantiation is a new function.
There will only be one, shared by all three classes. If you want separate instances, you will have to create separate functions in the derived classes.
There will only be one instance of x
in the entire program. A nice work-around is to use the CRTP:
template <class Derived>
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base<A> { };
class B : public Base<B> { };
This will create a different Base<T>
, and therefore a distinct x
, for each class that derives from it.
You may also need a "Baser" base to retain polymorphism, as Neil and Akanksh point out.