C++ has three access specifiers: public, private and protected. Each one decides which code can use the members listed under it. public members are open to any code that can see the class, private members are limited to the class and its friends, and protected members also reach derived classes. C++ uses the term access specifier, while many other languages say access modifier for the same idea.
public
public members form the interface of the class, the functions other code is meant to call. Any code that can see the class can use them.
private
private members hold internal state. Only the class’s own member functions and its friends can use them. Changing them through member functions lets the class keep its data valid.
protected
protected members are for base classes that want derived classes to reach some internal data while keeping it away from ordinary outside code. The class itself, its friends and derived classes can use them. Other code cannot.
Who can reach each one
| Specifier | Same class | Derived class | Friend | Other code |
|---|---|---|---|---|
public |
Yes | Yes | Yes | Yes |
protected |
Yes | Yes | Yes | No |
private |
Yes | No | Yes | No |
A Vehicle example
#include <iostream>
class Vehicle {
public:
void start() { std::cout << "Starting\n"; }
protected:
int wheels = 4;
private:
int serialNumber = 12345;
};
class Motorcycle : public Vehicle {
public:
Motorcycle() { wheels = 2; } // OK: wheels is protected in the base class
};
int main() {
Motorcycle m;
m.start(); // OK: public
// m.wheels = 3; // error: wheels is protected
// int s = m.serialNumber; // error: serialNumber is private
}
Which one to use
- Make data members
privateby default, and expose what callers need throughpublicfunctions. - Use
publicfor the functions that form the class’s interface. - Use
protectedonly when you design a base class that derived classes are meant to extend.
Access Modifiers in C++ puts all three into context, with the defaults and friends. Encapsulation in C++ explains why private data is worth the extra functions, and Friend Functions in C++ covers how a friend can still reach private members.