简体   繁体   中英

static member variable of a subclassed class

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
}

A very odd use of inheritance indeed. The base class is supposed to define interfaces ideally and contain as little or no state at all if possible according to good OO design principle.

This works because your foo() resets the value of A::s everytime it is called. Try printing the address of A::s . There is one and only one object. This will not work if you don't set the value everytime and you have multiple objects using another member function bar() to read the value of A::s.

You may run into sync issues if B and C objects are created in separate threads as well. You will end up with UB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM