🔐 C++ Access Specifiers – public, private, and protected Explained Simply
Access specifiers in C++ decide who can touch what inside a class. Think of them as locks on the doors to your class members.
🏷️ The Three Main Access Levels
- public – Anyone can access
- private – Only the class itself can access
- protected – The class and its children (inherited classes) can access
🔧 Example: public vs private
#include <iostream>
using namespace std;
class Car {
public:
string brand; // Anyone can access
private:
int engineSecret; // Only Car class can access
public:
Car() {
brand = "Toyota";
engineSecret = 1234;
}
void showInfo() {
cout << "Brand: " << brand << endl;
cout << "Engine Secret: " << engineSecret << endl;
}
};
int main() {
Car myCar;
myCar.brand = "Honda"; // OK
// myCar.engineSecret = 9999; // ❌ Error: private member
myCar.showInfo();
return 0;
}
📦 protected in Inheritance
When using protected, the base class allows its child classes to access certain members—like giving family members a spare key. 🔑
🔍 Summary Table (Quick Look)
- public: Access from anywhere
- private: Access only from within the class
- protected: Access from within the class and subclasses
🧠 Summary
- Access specifiers protect your data
- Use private to hide sensitive stuff
- Use public for safe open access
- Use protected with inheritance
With access specifiers, you’re now in control of what’s public and what’s private—like a coding bouncer! 🚪