ภาพรวม
Protected Members ใน C++ คล้าย Private Members ที่เข้าถึงจากภายนอกไม่ได้ แต่แตกต่างตรงที่ Derived Classes (คลาสลูก) เข้าถึงได้ ทำให้เหมาะสำหรับข้อมูล/ฟังก์ชันที่ Base Class ต้องการให้ลูกเข้าถึงแต่ไม่ให้ Public
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
class Base {
protected:
int num = 7; // Protected Member
};
class Derived : public Base {
public:
void func() {
// เข้าถึง Protected Member จาก Base ได้
cout << "The value of num is: " << num;
}
};
int main() {
Derived obj;
obj.func(); // เรียกผ่าน Public Interface
return 0;
}
ผลลัพธ์
The value of num is: 7
รายละเอียดการเข้าถึง
| บริบท | Public | Protected | Private |
|---|---|---|---|
| Base Class Methods | ✅ | ✅ | ✅ |
| Derived Class Methods (Public Inheritance) | ✅ | ✅ | ❌ |
| Derived Class Methods (Protected Inheritance) | Protected | Protected | ❌ |
| Derived Class Methods (Private Inheritance) | Private | Private | ❌ |
| Outside Code (main, other functions) | ✅ | ❌ | ❌ |
| Friend Functions/Classes | ✅ | ✅ | ✅ |
Protected Inheritance vs Public Inheritance
// Public Inheritance: "Is-A" Relationship
class DerivedPublic : public Base {
// Base::protected → Derived::protected
// Base::public → Derived::public
};
// Protected Inheritance: "Implemented-In-Terms-Of"
class DerivedProtected : protected Base {
// Base::protected → Derived::protected
// Base::public → Derived::protected
};
// Private Inheritance: "Implemented-In-Terms-Of" (Strict)
class DerivedPrivate : private Base {
// Base::protected → Derived::private
// Base::public → Derived::private
};
เมื่อไหร่ควรใช้ Protected?
- Data Members ที่ Derived Class ต้อง Read/Write โดยตรง (Performance, Convenience)
- Helper Functions ที่ใช้ภายใน Hierarchy เท่านั้น
- Virtual Functions ที่ Derived Class ต้อง Override/Extend
- Construction/Destruction Helpers (เช่น
init(),cleanup())
ข้อควรระวัง
- Protected Data = Breaks Encapsulation: Derived Class เปลี่ยนค่าได้อิสระ → Base Class ไม่ควบคุม Invariant ได้ → ใช้ Protected Methods แทนถ้าเป็นไปได้
- Tight Coupling: การเปลี่ยน Base Class Protected Members ส่งผลต่อ Derived Classes ทั้งหมด
- Prefer Private + Protected Accessors:
class BetterBase {
private:
int value_ = 0;
protected:
int getValue() const { return value_; }
void setValue(int v) {
if (v >= 0) value_ = v; // Validation/Invariant
}
};
สรุป
- Protected = Private + Derived Class Access ใช้ Protected Methods มากกว่า Protected Data
- Public Inheritance รักษา Protected เป็น Protected
- Friend Classes เข้าถึง Protected ได้เสมอ