Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ override inherited methods

Tags:

I have the following two classes. Since Child inherits from Father, I think that Child::init() overrides Father::init(). Why, when I run the program, I get "I'm the Father" and not "I'm the Child"? How to execute Child::init()?

You can test it here: https://ideone.com/6jFCRm

#include <iostream>

using namespace std;

class Father {
    public:
        void start () {
            this->init();
        };

        void init () {
            cout << "I'm the father" << endl;
        };
};

class Child: public Father {
    void init () {
        cout << "I'm the child" << endl;
    };
};

int main (int argc, char** argv) {
    Child child;
    child.start();
}
like image 811
pistacchio Avatar asked Oct 26 '15 15:10

pistacchio


People also ask

Can you override inherited methods?

To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method. Any method that is called must be defined within its own class or its superclass.

Does overriding require inheritance?

Compile time polymorphism or method overloading does not require inheritance.

What is function overriding in inheritance?

Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members, and the member functions present in the parent class.

Is there overriding in C?

Master C and Embedded C Programming- Learn as you go The function overriding is the most common feature of C++. Basically function overriding means redefine a function which is present in the base class, also be defined in the derived class. So the function signatures are the same but the behavior will be different.


1 Answers

Currently Child::init is hiding Father::init, not overriding it. Your init member function needs to be virtual in order to get dynamic dispatch:

virtual void init () {
    cout << "I'm the father" << endl;
};

Optionally, you could mark Child::init as override to be explicit that you want to override a virtual function (requires C++11):

void init () override {
    cout << "I'm the child" << endl;
};
like image 69
TartanLlama Avatar answered Nov 15 '22 12:11

TartanLlama