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();
}
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.
Compile time polymorphism or method overloading does not require 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.
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.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With