3

I have the following class declarations:

class human
{
    public:
    void msg(){cout<<"I am human\n";}
};
class John:public human 
{
    public:
    void msg(){cout<<"I am a John\n";}
};

As it is clear the class John and human both have a function msg(). Clearly , the class John is inheriting resources from human. Now when I create an object of the derived class and call msg():

John a;
a.msg();

The output is :

I am John

But doesnt John inherit msg() from human?

Also is there a way to access msg() of human by using an object of the derived class?

EDIT:

Yup calling the function like so will help me

a.human::msg()

Another question :

Also if I modify the class like so:

class human
{
    protected:
    void msg(){cout<<"I am human\n";}
};
class John:public human 
{
    public:
    void msg(){cout<<"I am a John\n";}
};

Now how can I access the msg() of human.

0

1 Answer 1

5

"But doesnt John inherit msg() from human?"

Yes it does, but hides it with its own implementation.

"Also is there a way to access msg() of human?"

Yes, you need to explicitly state the class scope (as long human::msg() is in public scope as it was originally asked):

  John a;
  a.human::msg();
 // ^^^^^^^

The same syntax needs to be applied if you want to access human::msg() from within class John:

class John : public human {
    public:
    void msg() {cout<<"I am a John\n";}
    void org_msg() { human::msg(); }
};

John a;
a.org_msg();

or another alternative

John john;
human* h = &john;
h->msg();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.