Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ลำดับการเรียก Constructor/Destructor ใน C++


ในบทเรียนนี้ เราจะอธิบายลำดับการเรียก Constructor และ Destructor ใน C++ เมื่อมี Inheritance

กฎลำดับ Constructor

  1. Base Class Constructor เรียกก่อน (จาก Base บนสุดลงมา)
  2. Member Object Constructor เรียกตามลำดับ宣告
  3. Derived Class Constructor เรียกทีหลัง

กฎลำดับ Destructor

กลับกัน Constructor: Derived → Member → Base (LIFO)

ตัวอย่าง

#include <iostream>
using namespace std;

class Parent {
public:
    Parent() { cout << "Parent Constructor\n"; }
    ~Parent() { cout << "Parent Destructor\n"; }
};

class Child : public Parent {
public:
    Child() { cout << "Child Constructor\n"; }
    ~Child() { cout << "Child Destructor\n"; }
};

int main() {
    Child obj;
    return 0;
}

ผลลัพธ์

Parent Constructor
Child Constructor
Child Destructor
Parent Destructor

หลายระดับ Inheritance

class Grandparent { ... };
class Parent : public Grandparent { ... };
class Child : public Parent { ... };

// Constructor: Grandparent → Parent → Child
// Destructor: Child → Parent → Grandparent

Multiple Inheritance

Base Classes เรียงตามลำดับใน Declaration List

class A { ... };
class B { ... };
class C : public A, public B { ... }; // A ก่อน B