简体   繁体   中英

Accessing to base class of derived class by derived class C++

The function whoAmI() is supposed to return:

I am a Man
I am a Omnivore

But it just returns "I am a Man" twice:

class Animal
{
public:
  string className;
};

class Omnivore:public Animal
{
 public:
    Omnivore()
    {
        className = "Omnivore";
    }
};

class Man:public Omnivore
{
public:
    Man() {
        className = "Man";
    }
     void whoAmI()
     {
         cout << "I am a " << Omnivore::className << endl;
         cout << "I am a " << Omnivore::Animal::className << endl;
     }
};

There's only one Animal::className , which is initialized to empty std::string by Animal 's constructor, then assigned to "Omnivore" by Omnivore 's constructor, then assigned to Man by Man 's constructor. So you got the same results, because they refer to same data member.

You can make them have their own data member with the same name; but note that it's not a good idea, the names in derived class will hide those in base class. eg

class Animal
{
public:
  string className;
};

class Omnivore:public Animal
{
 public:
    string className;
    Omnivore()
    {
        className = "Omnivore";
    }
};

class Man:public Omnivore
{
public:
    string className;
    Man() {
        className = "Man";
    }
     void whoAmI()
     {
         cout << "I am a " << Omnivore::className << endl;         // "Omnivore"
         cout << "I am a " << Omnivore::Animal::className << endl; // empty
         cout << "I am a " << className << endl;                   // "Man"
     }
};

It is usually done this way:

class Animal
{
public:
  static string className() { return "Man"; };
};

class Omnivore:public Animal
{
public:
  static string className() { return "Omnivore"; };
  void whoAmI()
  {
      cout << "I am a " << Omnivore::className() << endl;
      cout << "I am a " << Animal::className() << endl;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM