Computer >> Máy Tính >  >> Lập trình >> C ++

Hàm hủy ảo thuần túy trong C ++

Có thể sử dụng hàm hủy ảo thuần túy trong C ++. Nếu một lớp chứa hàm hủy ảo thuần túy, nó phải cung cấp một phần thân hàm cho hàm hủy thuần ảo.

Mã mẫu

#include <iostream>
using namespace std;

class B {
   public:
   virtual ~B()=0; // Pure virtual destructor
};

B::~B() {
   std::cout << "Pure virtual destructor is called";
}

class D : public B {
   public:
   ~D() {
      cout << "~D() is executed"<<endl;
   }
};

int main() {
   B *bptr=new D();
   delete bptr;
   return 0;
}

Đầu ra

~D() is executed
Pure virtual destructor is called