2

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?

  • possible duplicate of [Are static variables in a base class shared by all derived classes?](http://stackoverflow.com/questions/1390913/are-static-variables-in-a-base-class-shared-by-all-derived-classes) –  Apr 04 '11 at 15:34
  • Ouch! I should read more carefully the answers O:) – José M. Benítez Apr 04 '11 at 15:41

2 Answers2

6

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

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"; }
};
Chris Card
  • 3,216
  • 20
  • 15