Access static const variable from derived classes

655 Views Asked by At

I want to set name property in each derived class. And also want to acess this value like Bar1::s_name . My below code doesn't work. So how should I archive my desire?

 class Parent {
   public:
     static std::string getName() {
       return s_name;
     }
     const static std::string s_name;
 };


 class Bar1 : public Parent {
   public:
     Bar1() : s_name("Bar1") {}
 };

 class Bar2 : public Parent {
   public:
     Bar2() : s_name("Bar2") {}
 };


 int main() {
   Bar1 b;
   b.getName();
   return 0;
 }
3

There are 3 best solutions below

0
On

Presumably you are wanting to use this in some polymorphic context. If so, you can't use static methods, because they don't exhibit polymorphic behaviour. Additionally, static members will be the same for every instance, including derived objects.

You probably want something like this:

class Parent {
   public:
     virtual std::string getName() {
       return "Parent";
     }
 };


 class Bar1 : public Parent {
   public:
     virtual std::string getName() override {
       return "Bar1";
     }
 };

 class Bar2 : public Parent {
   public:
     virtual std::string getName() override {
       return "Bar2";
     }
 };

If you also want to be able to access the name statically like Bar1::s_name, you need a static member for each class:

class Parent {
   public:
     virtual std::string getName() {
       return s_name;
     }
     const static std::string s_name;
 };

 const std::string Parent::s_name = "Parent";

 //likewise for the others
0
On

I thing you do not understand properly what static (in this context) means.
Variable defined as static in class means, that there is only one instance of it. So s_name in both Bar1 and Bar2 adresses to one variable.
Method defined as static in class means, that it is not bound to specific instance of that class, but rather to all (maybe none) instances of that class. So it is better to call static method using B::getName() instead of b.getName() (it is less confusing).

Also, because you defined s_name as const static you made that a constant, which compiler does even treat like a variable in runtime, but rather like a constant.

0
On

you should define all static variable. definition is missing in your code. add below line to your program, it will work.

string Parent::s_name = "\0";