David
David

Reputation: 63

Editing functions in child class

I want to edit an inherited function name(), and ensure that the inherited function info() will call child::name() rather than parent::name() when called by an instance of child.

class parent {
public:
    string name() { return "parent"; }

    void info() {
        cout << "This class is " << name() << endl;
    }
};

class child : public parent {
public:
    string name() { return "child"; }
};

int main() {
    parent p;
    child c;
    p.info(); // outputs "parent"
    c.info(); // outputs "parent" - I want "child"
}

How can I get c.info() to use child::name()? I will never need name() outside of info(), and I don't really want to duplicate info() in the child class, as I am trying to avoid repeating a rather long block of code in my real problem.

Upvotes: 2

Views: 720

Answers (1)

Christophe
Christophe

Reputation: 73446

You have declared a non polymorphic function

If a member function f() of your parent is not virtual, it is not polymorphic. So if this function is called by another function of the parent, it is parent::f() that will be called.

If this function is hidden by another function f() in the child, with exactly the same signature, and if this function is called by another function of the child, it is child::f() that will be called.

Interestingly, if you invoke the function directly for an object, the function of the declared type of the object will be invoked.

Polymorphic functions

If you want to make your function polymorphic, you have to define it as virtual in the parent. Suppose it is overriden in the child. In this case, when you call f(), it will always be the f() defined for the real type of the object.

class parent {
public:
    virtual string name() { return "parent"; }

    ...
    }
};

class child : public parent {
public:
    string name() override { return "child"; }
};

With this programm, you'll get this result:

This class is parent
This class is child

Upvotes: 2

Related Questions