虚函数
调用虚函数时函数行为将根据对象所属类的不同而变化。
父类指针或引用指向子类对象时,可访问子类重写方法( virtual函数)但无法访问在父类中没有定义的子类方法和数据成员。
#include <iostream> using namespace std; class Super { public: Super(){} virtual void where(){cout<<"there is Super"<<endl;} }; class Sub :public Super { public: Sub(){} virtual void where(){cout<<"there is Sub"<<endl;} void what(){cout<<"what?";} }; int main() { Sub sub; Super* ptr = ⊂ Super &ref = sub; sub.where(); ptr->where(); ref.where(); return 0; }
运行结果:
通过ptr和ref访问的where()均为子类方法,无法访问子类的what()方法。
所有析构函数都应该声明为虚函数(至少祖先类的析构函数应声明为virtual)
一个函数被声明为virtual即使在它子类中没有显式的指出该函数依然是virtual。
如果父类的析构函数没有声明为virtual,当delete一个实际指向子类对象的父类指针时,析构函数调用链将被破坏。
#include <iostream> using namespace std; class Something { public: Something(){cout <<"1";} ~Something(){cout<<"1";} }; class Super : public Something { public: Super(){cout<<"2";} ~Super(){cout<<"2";} }; class Sub :public Super { public: Sub(){cout<<"3";} ~Sub(){cout<<"3";} }; int main() { Super* ptr = new Sub; delete ptr; return 0; }
运行结果:
将Something的析构函数声明为virtual后,结果就为“123321”了。
原文:http://www.cnblogs.com/baiyideng/p/3601452.html