Public vs Private vs Protected in C++: Key Differences and Usage
public members are accessible from anywhere, private members are accessible only within the class itself, and protected members are accessible within the class and its derived classes. These access specifiers control how class data and functions can be used to protect data and enforce encapsulation.Quick Comparison
This table summarizes the main differences between public, private, and protected access specifiers in C++.
| Access Specifier | Access Within Class | Access in Derived Classes | Access Outside Class | Typical Use Case |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Interface members accessible to all |
| private | Yes | No | No | Internal data hidden from outside |
| protected | Yes | Yes | No | Members for use in class and subclasses |
Key Differences
public members are fully accessible from anywhere in the program, including outside the class and in derived classes. This makes them suitable for functions and data that form the class's interface.
private members are only accessible inside the class itself. Neither derived classes nor outside code can access them directly. This protects sensitive data and implementation details from accidental misuse.
protected members are a middle ground: they are hidden from outside code but accessible to derived classes. This allows subclasses to use or modify base class internals while still restricting access from unrelated code.
Code Comparison
Example showing public members in a class:
class MyClass { public: int value; void show() { std::cout << "Value: " << value << std::endl; } }; int main() { MyClass obj; obj.value = 10; // Allowed because value is public obj.show(); // Allowed return 0; }
Private and Protected Equivalent
Example showing private and protected members and access from derived class:
class Base { private: int secret = 42; protected: int shared = 100; public: void show() { std::cout << "Secret: " << secret << ", Shared: " << shared << std::endl; } }; class Derived : public Base { public: void access() { // std::cout << secret; // Error: private member std::cout << "Shared from derived: " << shared << std::endl; // Allowed } }; int main() { Derived d; d.access(); d.show(); // std::cout << d.shared; // Error: protected member return 0; }
When to Use Which
Choose public when you want members to be accessible from anywhere, typically for the class interface.
Choose private to hide data and implementation details strictly inside the class, preventing outside or derived class access.
Choose protected when you want to allow derived classes to access or modify members but keep them hidden from outside code.
Key Takeaways
public for members meant to be accessed by all code.private to fully hide members from outside and derived classes.protected to allow access only to derived classes.