Reputation: 435
Well, apparently, I cannot. But that's my problem. Maybe it's a design issue and I'm getting the whole thing wrong.
I would like to have a class member initialized differently within each derived class. Imagine I have an object of type Device
. This Device
is just an interface used by the application code, because the actual devices are just one of two types, DeviceA
or DeviceB
. There are some features common to all devices, like, say, the name. That should be then a class member, shouldn't it? So I'd have:
class Device {
static std::string sm_name;
}
But each family device has its own name. How could I initialize the name to a different value for each derived class? Is the design wrong? Should the name property not be a class member?
Upvotes: 2
Views: 1835
Reputation: 3266
why not just have a virtual member function which returns the name, and implement it in the derived class to return the correct name?
e.g.
class A
{
public:
virtual std::string name() = 0;
};
class B : public A
{
public:
virtual std::string name() { return "typeB"; }
};
class C : public A
{
public:
virtual std::string name() { return "typeC"; }
};
Upvotes: 2
Reputation: 564383
Should the name property not be a class member?
Each family device should, most likely, have it's own, private static member. You could use a virtual method to return the proper name on a device instance.
Upvotes: 6