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

Access Modifiers ใน C++ (Public, Private, Protected)

Access Modifiers (ตัวกำหนดการเข้าถึง) ใช้สำหรับ Data Hiding (การซ่อนข้อมูล) ใน OOP ควบคุมว่าใครสามารถเข้าถึงสมาชิกของคลาสได้บ้าง

สรุป 3 ระดับการเข้าถึง

Modifier ภายในคลาส Derived Class ภายนอกคลาส
public✓✓✓
protected✓✓✗
private✓✗✗

1. Public Access Modifier

เข้าถึงได้จากที่ไหนก็ได้

#include <iostream>
using namespace std;

class Add {
public:
    int a, b;
    
    void sum() {
        cout << "Sum of " << a << " and " << b << " is " << a + b;
    }
};

int main() {
    Add obj;
    obj.a = 2;      // เข้าถึงได้
    obj.b = 5;      // เข้าถึงได้
    obj.sum();      // เรียกใช้ได้
    return 0;
}

ผลลัพธ์

Sum of 2 and 5 is 7

2. Private Access Modifier

เข้าถึงได้เฉพาะในคลาสเดียวกัน (และ friend)

#include <iostream>
using namespace std;

class Add {
private:
    int a, b;  // ซ่อนข้อมูล
    
public:
    void setData(int x, int y) {  // Setter
        a = x;
        b = y;
    }
    
    void sum() {  // ใช้ข้อมูลภายใน
        cout << "Sum of " << a << " and " << b << " is " << a + b;
    }
};

int main() {
    Add obj;
    // obj.a = 2;  // ❌ Error: private
    obj.setData(9, 5);  // ✓ ผ่าน public method
    obj.sum();
    return 0;
}

ผลลัพธ์

Sum of 9 and 5 is 14

3. Protected Access Modifier

เหมือน private แต่ Derived Class เข้าถึงได้

#include <iostream>
using namespace std;

class Parent {
protected:
    int a, b;  // Derived class เข้าถึงได้
};

class Child : public Parent {
public:
    void setData(int x, int y) {
        a = x;  // ✓ เข้าถึง protected ได้
        b = y;
    }
    
    void display() {
        cout << "a = " << a << ", b = " << b << endl;
    }
};

int main() {
    Child obj;
    obj.setData(9, 1);
    obj.display();
    // obj.a = 5;  // ❌ Error: protected จากภายนอก
    return 0;
}

ผลลัพธ์

a = 9, b = 1

Best Practices

หลักการ คำอธิบาย
Encapsulationทำ Data Members เป็น private เสมอ
Interfaceให้ Public Methods (getters/setters) ควบคุมการเข้าถึง
Inheritanceใช้ protected สำหรับข้อมูลที่ Derived Class ต้องใช้
Friendใช้ friend class/function เฉพาะที่จำเป็นจริงๆ

Default Access Specifier

  • class: default เป็น private
  • struct: default เป็น public

class MyClass {
    int x;  // private โดย default
};

struct MyStruct {
    int x;  // public โดย default
};

Friend Function/Class

ข้อยกเว้น - เข้าถึง private/protected ได้

class Box {
private:
    int width;
    friend void printWidth(Box b);  // Friend function
    friend class BoxManager;        // Friend class
};

void printWidth(Box b) {
    cout << b.width;  // ✓ เข้าถึง private ได้
}