Skip to content

Public / Private / Protected

Access specifiers control who can access the members of a class.

  • public → accessible everywhere
  • private → accessible only within the class
  • protected → accessible within class + derived classes

Basic Example

cpp
class Person {
public:
    string name;      // accessible everywhere
protected:
    int age;           // accessible in class + derived classes
private:
    string password;   // accessible only inside this class
};

int main() {
    Person p;
    p.name = "Alice";     // OK — public
    p.age = 25;             // ERROR — protected
    p.password = "1234";    // ERROR — private
}

Access Table

Same ClassDerived ClassOutside Class
publicYesYesYes
protectedYesYesNo
privateYesNoNo

Inheritance + Access Specifiers

cpp
class Base { public: int x; protected: int y; private: int z; };

// Public Inheritance (most common):
class Derived : public Base {
    // x → public (stays public)
    // y → protected (stays protected)
    // z → not accessible
};

// Protected Inheritance:
class Derived : protected Base {
    // x → protected (demoted)
    // y → protected
};

// Private Inheritance:
class Derived : private Base {
    // x → private (demoted)
    // y → private (demoted)
};

Full Inheritance Access Table

Base MemberPublic InheritanceProtected InheritancePrivate Inheritance
publicpublicprotectedprivate
protectedprotectedprotectedprivate
privateNot accessibleNot accessibleNot accessible

Friend — Special Access

cpp
class Box {
private:
    int length = 10;
    friend class BoxHelper;      // BoxHelper can access private members
    friend void printBox(Box);    // function can access private members
};

friend breaks encapsulation — use sparingly.

Struct vs Class

cpp
struct MyStruct { int x; }; // public by default
class MyClass { int x; };    // private by default
// Only difference between struct and class in C++ is default access.

Key Points

PointDetail
Default in classprivate
Default in structpublic
Protected useInheritance scenarios
Private useEncapsulation
FriendBypasses access rules
Most used inheritancepublic

One-liner: "Public members are accessible everywhere, private only within the class, and protected within the class and its derived classes — controlling encapsulation and inheritance behavior."