Access Modifiers Public, Private, Protected - Rybd04/2143-OOP GitHub Wiki

Definition

Access Modifiers (Public, Private, Protected)

Access modifiers in C++ control the visibility and accessibility of class members.

Public

Members declared as public are accessible from anywhere in the program. Any code can read or modify these members.

Private

Members declared as private are only accessible inside the class. They cannot be accessed or modified directly from outside the class. You need special functions (like getters and setters) to interact with private members.

Protected

Members declared as protected are accessible within the class and its derived classes (subclasses), but not from outside the class hierarchy.

Explanation

Public

Public is like a toy you can share with all your friends. Anyone can play with it.

Private

Private is like a secret toy you keep in a box. Only you can play with it, but you can give your friends a special way to play with it if you want.

Protected

Protected is like a toy you share with your family, but not with everyone. Your family can play with it, but not your friends.

Basic Code Example

class Car {
public:
    int speed;  // Public member

    void accelerate() {
        speed += 10;  // Increases speed
    }
};

class Car {
private:
    int speed;  // Private member

public:
    void setSpeed(int s) {
        if (s > 0) {  // Setting speed only if it's positive
            speed = s;
        }
    }

    int getSpeed() {
        return speed;
    }
};
class Car {
protected:
    int speed;  // Protected member
};

class SportsCar : public Car {
public:
    void accelerate() {
        speed += 20;  // Derived class can access protected member
    }
};

Image

image

Additional Resources

https://www.w3schools.com/cpp/cpp_access_specifiers.asp https://www.geeksforgeeks.org/access-modifiers-in-c/