欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c++中虚析构函数的作用

程序员文章站 2024-02-26 22:06:58
...
#include <iostream>
using namespace std;
class Base{
    public:
        Base(){
            cout<<"这是父亲的构造函数"<<endl; 
        }
        virtual ~Base()
        {
            cout<<"这是父亲的析构函数"<<endl; 
        }
        virtual void DoSomething()
        {
            cout<<"Do something in class Base!"<<endl;
        }
}; 
class Derived:public Base{
    public:
        Derived(){
            cout<<"这是儿子的构造函数"<<endl; 
        }
        ~Derived(){
            cout<<"这是儿子的析构函数"<<endl; 
        }
        void DoSomething(){
            cout<<"Do something in class Derived!"<<endl;
        }

};
int main(){
    Derived *pTest1 = new Derived();
    pTest1->DoSomething();
    delete pTest1;

    cout<<endl;
    Base *pTest2 = new Derived();
    pTest2->DoSomething() ;
    delete pTest2;
    return 0;
}

结果

c++中虚析构函数的作用

要是去掉~Base()析构函数前的virtual关键字,则子类的析构函数不会被调用,这样会造成内存泄漏。