How to call a parent class function from derived class function?


How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?

5/2/2014 11:43:53 PM

Accepted Answer

I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.

class left {
    void foo();

class right {
    void foo();

class bottom : public left, public right {
    void foo()
        //base::foo();// ambiguous

        // and when foo() is not called for 'this':
        bottom b;
        b.left::foo();  // calls from 'left'
        b.right::foo();  // call from 'right'

Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

class bottom : public left, public left { // Illegal
1/11/2017 9:48:20 AM

Given parent class named Parent and child class named Child, you can do something like this:

class Parent {
    virtual void print(int x);

class Child : public Parent {
    void print(int x) override;

void Parent::print(int x) {
    // some default behavior

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print

Note that Parent is the class's actual name and not a keyword.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow