Is it OK to have a static member variable defined in a base class, and having several derived classes each using its own instance of this member variable?
The following code compiles successfully, and prints the right output, but I am still not sure that doing something like that is a good practice. In the following example, how can it work, if I explicitly define only one instance of s (by calling: string A::s;) but I actually use 2 instances?
class A
{
protected:
void SetS(string new_s){s = new_s;}
void PrintS(){cout << s << endl;};
private:
static string s;
};
class B : public A
{
public:
void foo(){ SetS("bbb"); PrintS();};
};
class C : public A
{
public:
void foo(){ SetS("ccc"); PrintS();};
};
string A::s;
int main()
{
B b;
b.foo(); // results in output: bbb
C c;
c.foo(); // results in output: ccc
b.foo(); // results in output: bbb
}