虚函数的起源是:想用基类指针管理该基类的所有继承类。
当基类指针指向继承类对象时,如果函数不是虚函数,调用的是基类的成员;如果函数是虚函数,调用的是继承类的成员。
为了实现多态,虚函数是必须的。如果析构函数不是虚函数,基类指针调用析构函数 就只会调用基类的析构函数,仅仅释放了基类的空间造成内存泄漏。
代码举例:
#include <bits/stdc++.h> using namespace std; class base { public: base(){cout<<"creating base"<<endl;} ~base(){cout<<"it is base destructing"<<endl;} void dosom(){cout<<"just do something in base"<<endl;} }; class pai:public base { public: pai(){cout<<"creating pai"<<endl;} ~pai(){cout<<"it's pai destructing"<<endl;} void dosom(){cout<<"just do something in pai"<<endl;} }; int main() { base *p=new base; p->dosom(); delete p; cout<<endl; pai *p1=new pai; p1->dosom(); delete p1; cout<<endl; base * fin=new pai; fin->dosom(); delete fin; cout<<endl; return 0; } /*output: creating base just do something in base it is base destructing creating base creating pai just do something in pai it's pai destructing it is base destructing creating base creating pai just do something in base it is base destructing //内存泄漏 */
使用虚函数:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class base 5 { 6 public: 7 base(){cout<<"creating base"<<endl;} 8 virtual~base(){cout<<"it is base destructing"<<endl;} 9 virtual void dosom(){cout<<"just do something in base"<<endl;} //add virtual at left 10 }; 11 12 class pai:public base 13 { 14 public: 15 pai(){cout<<"creating pai"<<endl;} 16 ~pai(){cout<<"it's pai destructing"<<endl;} 17 void dosom(){cout<<"just do something in pai"<<endl;} 18 }; 19 int main() 20 { 21 base * fin=new pai; 22 fin->dosom(); 23 delete fin; 24 cout<<endl; 25 return 0; 26 } 27 /*output: 28 creating base 29 creating pai 30 just do something in base //without virtual wrong answer happened 31 it's pai destructing 32 it is base destructing 33 */ 34 //if virtual void dosom(){cout<<"just do something in base"<<endl;} //add virtual at left 35 /*output: 36 creating base 37 creating pai 38 just do something in pai //accepted 39 it's pai destructing 40 it is base destructing 41 */