Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Inheritance member functions using static variables

I am trying to convert some Python classes into c++ but am having some trouble. I have a Base class which has a class (static) variable and a method which returns it. I also have a derived class which overrides the class (static) variable like so,

In Python:

class Base:
   class_var = "Base"
   @classmethod
   def printClassVar(cls):
      print cls.class_var

class Derived(Base):
   class_var = "Derived"

d = Derived()
d.printClassVar()

which prints out the desired derived class variable, "Derived". Any idea how I can get the same functionality in c++? I have tried but end up getting the class variable of the Base class.

In c++

class Base
{
public:
    static void printStaticVar(){cout << s_var << endl;}
    static string s_var;
};
string Base::s_var = "Base";

class Derived : public Base
{
public:
    static string s_var;
};
string Derived::s_var = "Derived";

void main()
{
    Derived d;
    d.printStaticVar();
}
like image 344
scruffyDog Avatar asked Oct 21 '22 21:10

scruffyDog


1 Answers

Write a virtual function which returns a reference to the static member:

class Base
{
public:
    void printStaticVar() {cout << get_string() << endl;}
    static string s_var;
    virtual string const& get_string() { return Base::s_var; }
};
string Base::s_var = "Base";

class Derived : public Base
{
public:
    static string s_var;
    virtual string const& get_string() { return Derived::s_var; }
};
string Derived::s_var = "Derived";

void main()
{
    Derived d;
    d.printStaticVar();
}

Note that printStaticVar shouldn't be static.


You could also make the string static local inside the getter:

class Base
{
public:
    void printStaticVar() {cout << get_string() << endl;}
    virtual string const& get_string() { 
        static string str = "Base";
        return str;
    }
};

class Derived : public Base
{
public:
    virtual string const& get_string() { 
        static string str = "Derived";
        return str;
    }
};

void main()
{
    Derived d;
    d.printStaticVar();
}
like image 189
Pubby Avatar answered Oct 24 '22 17:10

Pubby