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;
}
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:
If you also want to be able to access the name statically like
Bar1::s_name
, you need a static member for each class: