C++ Access Specifiers
Access specifiers control who may use the members of a class. They are the language feature behind encapsulation: you decide which parts of a class form its public interface and which parts are internal details.
The three specifiers
| Specifier | Accessible from |
|---|---|
public |
anywhere — any code that has the object |
private |
only member functions (and friends) of the same class |
protected |
the class itself and classes derived from it |
An access specifier applies to every member below it until the next specifier:
#include <iostream>
#include <string>
using namespace std;
class Thermostat {
public:
void setTarget(double celsius) {
if (celsius >= 5 && celsius <= 30) {
target = celsius;
} else {
cout << "Rejected " << celsius << " (allowed 5-30)\n";
}
}
double getTarget() const { return target; }
private:
double target = 20;
};
int main() {
Thermostat t;
t.setTarget(23.5);
t.setTarget(80);
cout << "Target: " << t.getTarget() << "\n";
// t.target = 80; // error: 'double Thermostat::target' is private
}Rejected 80 (allowed 5-30)
Target: 23.5
Because target is private, the only way to change it is through setTarget, which enforces the allowed range. No code anywhere can put the thermostat into an invalid state.
What the compiler says
Trying to touch a private member from outside is a compile-time error, not a runtime one:
class Vault {
private:
int pin = 4321;
};
int main() {
Vault v;
v.pin = 0; // error: 'int Vault::pin' is private within this context
}protected and inheritance
protected members are hidden from the outside world, but derived classes can use them. Here Sensor keeps its raw reading protected so that subclasses can build on it:
#include <iostream>
using namespace std;
class Sensor {
public:
void update(double value) { raw = value; }
protected:
double raw = 0; // visible to derived classes
private:
int serial = 1001; // visible only inside Sensor
};
class FahrenheitSensor : public Sensor {
public:
double fahrenheit() const {
return raw * 9 / 5 + 32; // OK: raw is protected
// serial is NOT accessible here
}
};
int main() {
FahrenheitSensor s;
s.update(25);
cout << s.fahrenheit() << "\n";
// cout << s.raw; // error: protected outside the class hierarchy
}77
Private means "private to the class", not "to the object"
Access is checked per class. A member function may access the private members of another object of the same class — handy for comparisons and copying:
#include <iostream>
using namespace std;
class Money {
public:
explicit Money(long cents) : cents(cents) {}
bool isMoreThan(const Money& other) const {
return cents > other.cents; // other's private member: allowed
}
Money plus(const Money& other) const {
return Money(cents + other.cents);
}
void print() const {
cout << cents / 100 << "." << (cents % 100 < 10 ? "0" : "") << cents % 100 << "\n";
}
private:
long cents;
};
int main() {
Money a(1250), b(399);
cout << boolalpha << a.isMoreThan(b) << "\n";
a.plus(b).print();
}true
16.49
Conventions
- Put the
publicsection first — it is what users of the class read. - Make data members
privateby default; expose behaviour through public methods. - Use
protectedsparingly. Protected data creates a tight coupling between base and derived classes.
Tip: Many style guides add a suffix or prefix to private members, such as
balance_orm_balance, so they are easy to tell apart from parameters and locals.
Test yourself
Which members can a derived class access in its base class?
- Only public
- public and protected
- public, protected and private
- None
When is an access violation such as obj.secret = 1; detected?
- At runtime
- At compile time
- Only in debug builds
- Never
Can a method of class Money read the private members of another Money object?
- Yes, access is per class
- No, only its own object
- Only if it is static
- Only with a cast