Multiple Inheritance: คลาสลูกสืบทอดจากหลายคลาสแม่ (มากกว่า 1) ได้ Features จากทุก Base Classes
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
class A {
public:
int a = 5;
A() { cout << "Constructor A\n"; }
};
class B {
public:
int b = 10;
B() { cout << "Constructor B\n"; }
};
class C : public A, public B {
public:
int c = 20;
C() {
cout << "Constructor C\n";
cout << "C inherits from A and B\n";
}
};
int main() {
C obj;
cout << "a = " << obj.a << endl;
cout << "b = " << obj.b << endl;
cout << "c = " << obj.c << endl;
return 0;
}
ผลลัพธ์
Constructor A
Constructor B
Constructor C
C inherits from A and B
a = 5
b = 10
c = 20
ลำดับการสร้าง (Construction Order)
- Base Classes ตามลำดับที่เขียนใน Inheritance List (
Aแล้วB) - Derived Class (
C)
ปัญหา Diamond Problem
ถ้า A และ B สืบทอดจาก Base เดียวกัน (เช่น Class Base) จะมี Base Sub-object 2 ตัวใน C → Ambiguity
แก้ด้วย Virtual Inheritance
class A : virtual public Base { ... };
class B : virtual public Base { ... };
class C : public A, public B { ... }; // มี Base เพียง 1 ตัว
ข้อควรระวัง
- Complexity สูง ใช้เฉพาะเมื่อจำเป็น
- Ambiguity: สมาชิกซ้ำชื่อ ใช้
obj.A::memberระบุ Scope - Size เพิ่มขึ้น (Multiple vptrs)