Destructors ใน C ++ เป็นฟังก์ชันของสมาชิกในคลาสที่ลบวัตถุ โดยจะเรียกเมื่อคลาสอ็อบเจ็กต์หมดขอบเขต เช่น เมื่อฟังก์ชันสิ้นสุด โปรแกรมสิ้นสุด เรียกใช้ตัวแปร delete เป็นต้น
Destructors นั้นแตกต่างจากฟังก์ชั่นของสมาชิกทั่วไปเนื่องจากไม่มีการโต้แย้งใด ๆ และไม่ส่งคืนสิ่งใด นอกจากนี้ destructors ยังมีชื่อเดียวกับคลาสและชื่อของพวกเขานำหน้าด้วย tilde(~)
โปรแกรมที่แสดงตัวทำลายล้างในภาษา C++ มีดังต่อไปนี้
ตัวอย่าง
#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;
} ผลลัพธ์
Inside Constructor num1 = 10 num2 = 20 Inside Destructor
ในโปรแกรมข้างต้น คลาส Demo มีคอนสตรัคเตอร์ที่ตั้งค่าเริ่มต้น num1 และ num2 ด้วยค่าที่จัดเตรียมโดย n1 และ n2 นอกจากนี้ยังมีฟังก์ชัน display() ที่พิมพ์ค่าของ num1 และ num2 นอกจากนี้ยังมี destructor ใน Demo ที่ถูกเรียกเมื่อขอบเขตของคลาสอ็อบเจ็กต์สิ้นสุดลง ข้อมูลโค้ดสำหรับสิ่งนี้มีดังต่อไปนี้
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";
}
}; ฟังก์ชัน main() มีการกำหนดอ็อบเจ็กต์สำหรับอ็อบเจ็กต์ประเภท Demo จากนั้นฟังก์ชัน display() จะถูกเรียก ดังแสดงด้านล่าง
Demo obj1(10, 20); obj1.display();