5

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();
}

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or, instead of having a static variable at all, simply return a constant, in this example. However that may not be suitable for all solutons.
0

Another possibility might be:

class Base
{
  const std::string var;
public:
  Base(std::string s="Base") : var(s) {}
  void printVar() { std::cout << var << std::endl }
};
class Derived : public Base
{
public:
  Derived(std::string s="Derived") : Base(s) {}
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.