Reputation: 58863
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();
}
Upvotes: 28
Views: 67643
Reputation: 1966
If you want the child to override the init method, you must make the init
method in the base class virtual
.
class Father {
public:
void start () {
this->init();
};
virtual void init () {
cout << "I'm the father" << endl;
};
};
A class that re-declares and re-implements a virtual method of one of its bases, is said to override that method. In order for late binding to occur for a method, you need to declare that method virtual
.
Upvotes: 3
Reputation: 310950
You should define the function with function specifier virtual
For example
#include <iostream>
using namespace std;
class Father {
public:
virtual ~Father() {}
void start () {
this->init();
};
virtual void init () const {
cout << "I'm the father" << endl;
};
};
class Child: public Father {
void init () const override {
cout << "I'm the child" << endl;
};
};
int main()
{
Child child;
child.start();
return 0;
}
Otherwise function start
searches name init
in the scope of its own class. And because function init
is not virtual that is it is not overriden in the derived class the base class function init is called.
Upvotes: 5
Reputation: 65610
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;
};
Upvotes: 40