Fundamentals 6 min read

Master C++ Access Modifiers: public, private, protected Explained with Real Code

This article thoroughly explains C++'s three access control modifiers—public, private, and protected—covering their definitions, differences, practical usage in classes, inheritance effects, friend functions, and best practices for encapsulation and maintainable OOP design.

php Courses
php Courses
php Courses
Master C++ Access Modifiers: public, private, protected Explained with Real Code

1. Access Control Basics

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

class MyClass {
public:
    // public member - accessible by any code
    int publicVar;
private:
    // private member - only class member functions can access
    int privateVar;
protected:
    // protected member - class and derived classes can access
    int protectedVar;
};

2. Detailed Explanation of public, private, protected

public

Any code can access public members

Usually used for the class interface part

class Person {
public:
    string name;
    void introduce() {
        cout << "Hello, I'm " << name << endl;
    }
};

int main() {
    Person p;
    p.name = "Alice"; // can access directly
    p.introduce(); // call public method
    return 0;
}

private

Only member functions of the class can access

Default access level if no specifier is given

Key to implementing encapsulation

class BankAccount {
private:
    double balance; // external code cannot access directly
public:
    void deposit(double amount) {
        if (amount > 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
    acc.deposit(1000); // must use public interface
    return 0;
}

protected

Accessible by the class and derived classes

Between public and private

Primarily used in inheritance hierarchies

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 members
    }
};

3. Practical Applications of Access Control

Data encapsulation best practice

class Temperature {
private:
    double celsius;
public:
    void setCelsius(double c) {
        celsius = c;
    }
    double getCelsius() {
        return celsius;
    }
    double getFahrenheit() {
        return celsius * 9 / 5 + 32;
    }
};

Access control in inheritance

Inheritance type affects the visibility of base class members in derived classes:

public inheritance: public stays public, protected stays protected, private becomes inaccessible.

protected inheritance: public and protected become protected, private remains inaccessible.

private inheritance: public and protected become private, private remains inaccessible.

4. Friend Functions and Friend Classes

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

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

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

5. FAQs and Best Practices

When to use private? Most data members should be private; provide getters/setters only when necessary.

When to use protected? For members intended to be accessed directly by derived classes, common in the Template Method pattern.

When to use public? For class interface methods and simple POD structures.

Avoid overusing friends: they break encapsulation; use only when necessary, such as for operator overloading.

Conclusion

public

: defines the external interface of the class. private: implements details, enforcing access through the interface. protected: reserved for derived class access.

Correct use of access control enhances code security, improves maintainability, reduces coupling, and makes interfaces clearer.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

COOPEncapsulationInheritanceAccess Modifiersfriend functions
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.