和普通的成员函数一样,虚成员函数同样可以被继承。我们只需要将基类中的display函数通过virtual关键字声明为虚函数,之后即使在派生类中display函数声明时未加上virtual关键字,但它在所有的派生类中都将自动成为虚函数。
#include<iostream>
using namespace std;
class base
{
public:
virtual void hello(){cout<<"Hello base!"<<endl;}
};
class derived: public base
{
public:
//void hello(){cout<<"Hello derived!"<<endl;}
};
class derivedson: public derived
{
void hello(){cout<<"Hello derivedson!"<<endl;}
};
int main()
{
base * p = new base;
p->hello();
delete p;
p = new derived;
p->hello();
delete p;
derived * pp = new derivedson;
pp->hello();
delete pp;
return 0;
}
Hello base!
Hello base!
Hello derivedson!