ภาพรวม
C++ มี Access Specifiers 3 ระดับ สำหรับควบคุมการเข้าถึง Class Members:
| Access Specifier | Same Class | Derived Class | Outside (Non-member) | Friend |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ❌ | ✅ |
| private | ✅ | ❌ | ❌ | ✅ |
Default: Class = private, Struct = public
รายละเอียด
Private Members
- เข้าถึงได้เฉพาะในคลาสเดียวกัน (Member Functions, Friend Functions/Classes)
- Derived Class ไม่สามารถเข้าถึง ได้โดยตรง ใช้สำหรับ: Implementation Details, Internal State, Invariants
Protected Members
- เข้าถึงได้ในคลาสเดียวกัน และ Derived Classes (Child Classes)
- Outside (Non-member) ไม่สามารถเข้าถึง ได้
- ใช้สำหรับ: ข้อมูล/ฟังก์ชันที่ Derived Class ต้องใช้แต่ไม่อยากให้ภายนอกเข้าถึง
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
class Base {
public:
int a = 8; // Public: ใครเข้าถึงได้
protected:
int b = 10; // Protected: Base + Derived เข้าถึงได้
private:
int c = 20; // Private: เฉพาะ Base เท่านั้น
};
class Derived : public Base {
public:
void func() {
cout << "The value of a (public): " << a << "\n";
cout << "The value of b (protected): " << b << "\n";
// cout << c; // ❌ Error: 'c' is private in Base
}
};
int main() {
Derived obj;
obj.func();
// obj.a = 5; // ✅ OK: Public
// obj.b = 5; // ❌ Error: Protected (Outside access)
// obj.c = 5; // ❌ Error: Private
return 0;
}
ผลลัพธ์
The value of a (public): 8
The value of b (protected): 10
Inheritance Types และ Access
| Base Access | Public Inheritance | Protected Inheritance | Private Inheritance |
|---|---|---|---|
| public | public | protected | private |
| protected | protected | protected | private |
| private | Inaccessible | Inaccessible | Inaccessible |
Best Practices
- Prefer Private: เริ่มจาก Private ทุกอย่าง เปิดเฉพาะที่จำเป็น
- Protected สำหรับ Extension: ใช้เมื่อ Derived Class ต้องเข้าถึงโดยตรง
- Getter/Setter: ให้ Public Access ผ่าน Methods แทน Data Members โดยตรง
- Friend แบบจำกัด: ใช้ Friend สำหรับ Classes ที่เกี่ยวข้องอย่างใกล้ชิด (Operator<<, Factory)
ข้อผิดพลาดทั่วไป
- ทำทุกอย่าง Public → Broken Encapsulation
- ทำทุกอย่าง Protected → ทำลาย Encapsulation ของ Base Class
- ลืมว่า Private ไม่ถูกสืบทอด (แต่ยังมีอยู่ใน Object Layout)