Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Pure virtual destructor trong C++


C++ cho phép pure virtual destructor. Nếu lớp có pure virtual destructor, nó trở thành abstract class. Bắt buộc phải định nghĩa body cho pure virtual destructor (ngoài khai báo =0), vì destructor lớp dẫn xuất gọi destructor cơ sở khi hủy.

Ví dụ

#include <iostream>
using namespace std;

class Base {
public:
    virtual ~Base() = 0; // Pure virtual destructor
};
Base::~Base() { cout << "Pure virtual destructor called\n"; } // Phải định nghĩa

class Derived : public Base {
public:
    ~Derived() { cout << "~Derived\n"; }
};

int main() {
    Base *b = new Derived();
    delete b; // Gọi ~Derived() rồi ~Base()
    return 0;
}

Kết quả

~Derived
Pure virtual destructor called