1

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; } }; 
6
  • 3
    There is only one className for a given this, regardless of how you refer to it. Commented Feb 1, 2018 at 16:54
  • 2
    Make className a (virtual or static) function, then it will work. Commented Feb 1, 2018 at 16:55
  • 2
    Check out the Definitive C++ Book Guide/List. Commented Feb 1, 2018 at 16:56
  • 2
    You cannot override data members. Commented Feb 1, 2018 at 16:56
  • 1
    Also, whoAmI() doesn't return anything - it's void. Commented Feb 1, 2018 at 16:56

2 Answers 2

1

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. e.g.

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" } }; 
Sign up to request clarification or add additional context in comments.

Comments

1

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; } }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.