C++中虚析构函数实例

来源:互联网 发布:java md5校验 编辑:程序博客网 时间:2024/06/05 20:57

/*
 * File:   main.cpp
 * Author: yubao
 *
 * Created on June 1, 2009, 11:47 PM
 */

#include <iostream>
using namespace std;

class Base
{
public:
   virtual ~Base()         //如果不声明为虚函数,那么派生类的析构函数不会被调用,造成内存泄露
    {
        cout<<"Base destrutor"<<endl;
    }
};

class Derived:public Base
{
public:
    Derived();
    ~Derived();
private:
    int *i_pointer;

};

Derived::Derived()
{
    i_pointer=new int(0);
}

Derived::~Derived()
{
    cout<<"Derived destructor"<<endl;
    delete i_pointer;
}

void fun(Base * b)
{
    delete b;
}
/*
 *
 */
int main(int argc, char** argv) {
    Base *b=new Derived();
    fun(b);

    return 0;
}

原创粉丝点击