0

I have written the following code:

// constructors and derived classes
#include <iostream>
using namespace std;

class Mother
{
  public:
    int age;
    Mother()
    {
        cout << "Mother: no parameters: \n"
             << this->age << endl;
    }
    Mother(int a)
    {
        this->age = a;
    }
    void sayhello()
    {
        cout << "hello my name is clair";
    }
};

class Daughter : public Mother
{
  public:
    int age;
    Daughter(int a)
    {
        this->age = a * 2;
    };
    void sayhello()
    {
        cout << "hello my name is terry";
    }
};

int greet(Mother m)
{
    m.sayhello();
}

int main()
{
    Daughter kelly(1);
    Son bud(2);
    greet(kelly);
}

and my question is this: Since kelly is an instances of a class derived from Mother it makes sense to me that I can pass it into a function that requires an object of type mother ie. greet. My question is this, is it possible to call the sayhello function from within greet such that it will say it will say "hello my name is terry" instead of "hello my name is clair".

2
  • Btw it probably doesn't make sense to declare an int age; in your Daughter class, since that variable already exists in the Mother class. If you declare it in the Daughter class as well, then every Daughter will have two ages, which is probably not what you intended. A better approach would be to write your Daughter constructor like this, so that the a argument gets passed up to Mother's constructor: Daughter(int a) : Mother(a*2) {} Commented Jan 16, 2019 at 1:49
  • This inheritance setup means that every Daughter is also a Mother. That doesn't make sense, but presumably because it's just an example. Commented Jan 16, 2019 at 5:30

1 Answer 1

2

What you're asking for is called "polymorphic behavior" (or "dynamic dispatch") and it is a basic feature of C++. To enable it, you'll need to do a couple of things:

  1. Tag your sayhello() methods with the virtual keyword (i.e. virtual void sayhello() rather than just void sayhello())

  2. Change the greet() method's argument to pass-by-reference or pass-by-pointer, to avoid object-slicing problems (i.e. int greet(const Mother & m) rather than int greet(Mother m))

Once you've done that, the compiler will intelligently choose which sayhello() method to call at run-time, based on the m argument's actual object-type, rather than hard-coding the choice at compile-time based on the type explicitly listed in the greet function's arguments-list.

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.