虚析构函数

什么是虚析构函数?

  • 虚析构函数确保继承类对象在析构的时候从继承类析构。

  • 经常用于子类对象被赋值给父类对象指针的情景。

例1:下面例子说明没有虚析构函数是对象析构顺序。

#include <iostream>
 
using namespace std;
 
class Base {
 
    public:
        Base() {
            cout << "Base class constructor ..." << endl;
        }
        ~Base() {
            cout << "Base class destructor ..." << endl;
        }
};
 
class Derived : public Base {
 
    public:
        Derived() {
            cout << "Derived class constructor ..." << endl;
        }
        ~Derived() {
            cout << "Derived class destructor ..." << endl;
        }
};
 
void main()
{
    Base* base;
    base = new Derived();
    delete base;
}
 
OUTPUT:
Base class constructor ...
Derived class constructor ...
Base class destructor ...

例2:下面例子说明有虚析构函数时对象析构顺序。

#include <iostream>
 
using namespace std;
 
class Base {
 
    public:
        Base() {
            cout << "Base class constructor ..." << endl;
        }
        virtual ~Base() {
            cout << "Base class destructor ..." << endl;
        }
};
 
class Derived : public Base {
 
    public:
        Derived() {
            cout << "Derived class constructor ..." << endl;
        }
        ~Derived() {
            cout << "Derived class destructor ..." << endl;
        }
};
 
void main()
{
    Base* base;
    base = new Derived();
    delete base;
}
 
OUTPUT:
Base class constructor ...
Derived class constructor ...
Derived class destructor ...
Base class destructor ...


你可能感兴趣的:(虚析构函数)