Trying to get a quick understanding of how virtual
functions work and not sure why the code below doesn't print any output. As far as I know, since moveMouth()
is virtual
, it should use the version of moveMouth()
in the talk
class.
/*
* main.cpp
*
* Created on: Mar 29, 2015
* Author: Admin
*/
#include <iostream>
using namespace std;
class talk{
public:
int a=5;
void moveMouth(){
cout <<"blah blah blah"<<endl;
}
};
class person : public talk {
public:
int id;
person(int a): id(a) {
}
virtual void moveMouth(){
//cout <<"word word word"<<endl;
}
};
int main(){
person* p = new person(0);
p->moveMouth();
return 0;
}
As far as I know, since
moveMouth()
isvirtual
, it should use the version ofmoveMouth()
in thetalk
class.
No, that's not how polymorphism works. It allows you to introduce different behavior in the derived class when used in the base class.
Your example calls the empty implementation of moveMouth()
from the person
class.
To call the base class version just omit the declaration in the derived class:
class person : public talk {
public:
int id;
person(int a): id(a) {
}
// Completely omit this if you want to call the base class function by default:
// virtual void moveMouth(){
//cout <<"word word word"<<endl;
// }
};
To allow to change the behavior, you must declare the function as virtual
in the base class:
class talk{
public:
int a=5;
virtual void moveMouth(){
// ^^^^^^^
cout <<"blah blah blah"<<endl;
}
};
The polymorphic behavior in the inheritance hierarchy starts from the point you first introduce a virtual
function.
As an aside:
Polymorphic behavior can be better demonstrated like this
int main(){
talk* t = new person(0);
t->moveMouth();
return 0;
}
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