C++ Learning Manual – Object-Oriented Programming (OOP) 31 – Access Control (public, private, protected)

One of the three main characteristics of Object-Oriented Programming (OOP) is encapsulation, which C++ implements through access control modifiers <span>public</span><span>private</span> and <span>protected</span>. This article will delve into the usage, differences, and practical application scenarios of these three access control modifiers.

1. Basic Concepts of Access Control

Access control modifiers determine the visibility and accessibility of class members:

class MyClass {
public:     // Public members - accessible by any code
    int publicVar;
    
private:    // Private members - accessible only by member functions of this class
    int privateVar;
    
protected:  // Protected members - accessible by this class and derived classes
    int protectedVar;
};

2. Detailed Explanation of the Three Access Controls

1. public (Public Members)
  • Any code can access public members
  • Usually used for the interface part of the class
class Person {
public:
    string name;
    
    void introduce() {
        cout &lt;&lt; "Hello, I'm " &lt;&lt; name &lt;&lt; endl;
    }
};

int main() {
    Person p;
    p.name = "Alice";  // Can be accessed directly
    p.introduce();     // Call public method
}
2. private (Private Members)
  • Only member functions of this class can access
  • Default access level (if no modifier is specified)
  • Key to implementing encapsulation
class BankAccount {
private:
    double balance;  // Cannot be accessed directly from outside
    
public:
    void deposit(double amount) {
        if (amount &gt; 0) {
            balance += amount;  // Member function can access private member
        }
    }
    
    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount acc;
    // acc.balance = 1000;  // Error! Cannot access private member directly
    acc.deposit(1000);     // Must operate through public interface
}
3. protected (Protected Members)
  • Accessible by this class and derived classes
  • Intermediate between public and private
  • Mainly used in inheritance systems
class Shape {
protected:
    int width, height;
    
public:
    void setDimensions(int w, int h) {
        width = w;
        height = h;
    }
};

class Rectangle :public Shape {
public:
    int area() {
        return width * height;  // Derived class can access protected member
    }
};

3. Practical Applications of Access Control

1. Best Practices for Data Encapsulation
class Temperature {
private:
    double celsius;
    
public:
    void setCelsius(double c) {
        celsius = c;
    }
    
    double getCelsius() {
        return celsius;
    }
    
    double getFahrenheit() {
        return celsius * 9/5 + 32;
    }
};
2. Access Control in Inheritance

The inheritance method affects the access level of base class members in derived classes:

Base Class Member \ Inheritance Method public Inheritance protected Inheritance private Inheritance
public public protected private
protected protected protected private
private not accessible not accessible not accessible
class Base {
public:
    int pub;
protected:
    int prot;
private:
    int priv;
};

class DerivedPublic :public Base {
    // pub is public, prot is protected, priv is not accessible
};

class DerivedProtected :protected Base {
    // pub and prot are both protected, priv is not accessible
};

class DerivedPrivate :private Base {
    // pub and prot are both private, priv is not accessible
};

4. Friend Functions and Friend Classes

Friends can bypass access restrictions, allowing specific functions or classes to access private members:

class SecretData {
private:
    int secretCode;
    
    friendclass TrustedClass; // Friend class
    friend void displaySecret(const SecretData&amp;);  // Friend function
};

class TrustedClass {
public:
    void showSecret(SecretData&amp; sd) {
        cout &lt;&lt; "Secret code: " &lt;&lt; sd.secretCode &lt;&lt; endl;
    }
};

void displaySecret(const SecretData&amp; sd) {
    cout &lt;&lt; "The secret is: " &lt;&lt; sd.secretCode &lt;&lt; endl;
}

5. Common Questions and Best Practices

  1. When to use private?

  • Most data members should be set to private
  • Provide getters/setters only when necessary
  • When to use protected?

    • For members that you plan to allow derived classes to access directly
    • Commonly used in template method design patterns
  • When to use public?

    • For interface methods of the class
    • For simple data aggregation classes (like POD structures)
  • Avoid overusing friends

    • Friends break encapsulation
    • Use only when necessary, such as for operator overloading

    Conclusion

    1. <span>public</span>: Defines the external interface of the class
    2. <span>private</span>: Implementation details, forcing access through the interface
    3. <span>protected</span>: Access rights reserved for derived classes

    Correct use of access control is key to good class design, as it:

    • Enhances code security
    • Improves maintainability
    • Reduces coupling
    • Makes interfaces clearer

    Remember: Good OOP design should work like a “black box” – users only need to know how to use the interface without needing to understand the internal implementation details.

    Java learning materials available

    C language learning materials available

    Frontend learning materials available

    C++ learning materials available

    PHP learning materials available

    Leave a Comment