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

Hàm hủy (Destructors) trong C++


Destructor (hàm hủy) là hàm thành viên xóa đối tượng. Được gọi khi đối tượng hết phạm vi: kết thúc hàm, kết thúc chương trình, gọi delete...

Đặc điểm: không tham số, không trả về, tên trùng lớp nhưng tiền tố dấu tilde (~).

Ví dụ

#include <iostream>
using namespace std;

class Demo {
private:
    int num1, num2;
public:
    Demo(int n1, int n2) {
        cout << "Inside Constructor" << endl;
        num1 = n1;
        num2 = n2;
    }
    void display() {
        cout << "num1 = " << num1 << endl;
        cout << "num2 = " << num2 << endl;
    }
    ~Demo() {
        cout << "Inside Destructor";
    }
};

int main() {
    Demo obj1(10, 20);
    obj1.display();
    return 0;
}

Kết quả

Inside Constructor
num1 = 10
num2 = 20
Inside Destructor

Lớp Demo với Constructor và Destructor

class Demo {
private:
    int num1, num2;
public:
    Demo(int n1, int n2) {
        cout << "Inside Constructor" << endl;
        num1 = n1;
        num2 = n2;
    }
    void display() {
        cout << "num1 = " << num1 << endl;
        cout << "num2 = " << num2 << endl;
    }
    ~Demo() {
        cout << "Inside Destructor";
    }
};

Hàm main()

Demo obj1(10, 20);
obj1.display();

Khi main() kết thúc, obj1 hết phạm vi → Destructor được gọi tự động.