The access specifiers public, private and protected in C++ decide who is allowed to touch the internals of a class. What they actually protect is not the data but the invariant, which is the rule that keeps the state of the class valid. A class with public members has no invariant, because anybody can put any value into them. A class with private members and public accessors can be changed later without breaking anybody.
The previous lesson in this module covered "What Do Constructors and Destructors Guarantee?", and the next lesson in this module is about "How Does const Correctness Harden a Class?".
The three levels of access
A class starts as private by default, and a struct starts as public. That is the only difference between a class and a struct in C++.
#include <iostream>
class Vehicle {
private:
int odometer; // only this class may touch it
protected:
int service_count; // this class and its derived classes
public:
std::string registration; // everyone may touch it
};
int main() {
Vehicle van;
van.registration = "VN-4471";
// van.odometer = 100; // does not compile: odometer is private
std::cout << "registration: " << van.registration << '\n';
return 0;
}The output shows the public member being set and used.
registration: VN-4471The commented-out line is a compile error, and the error message names the member and the class, which is one of the friendliest diagnostics that the language produces.
Why private beats public
A public member is a promise that the value will stay sensible for ever. A private member is not a promise at all.
#include <iostream>
class Vehicle {
public:
Vehicle() : odometer(0), service_due(10000) {}
void service() {
odometer = 0;
service_due = 10000;
}
int miles_until_service() const {
return service_due - odometer;
}
void drive(int miles) {
if (miles < 0) {
return;
}
odometer += miles;
}
private:
int odometer;
int service_due;
};
int main() {
Vehicle van;
van.drive(9000);
std::cout << "miles until service: " << van.miles_until_service() << '\n';
van.drive(2000);
std::cout << "miles until service: " << van.miles_until_service() << '\n';
van.service();
std::cout << "after service: " << van.miles_until_service() << '\n';
return 0;
}The output shows the class controlling its own state.
miles until service: 1000
miles until service: -1000
after service: 10000Nobody outside the class can set the odometer backwards or set it to a negative number, because there is no way to reach it. The class can be changed internally, whether that is the units, the service interval or the way that the counter is stored, and no caller will notice.
Accessors and the naming convention
The usual pattern is a private member plus a public getter and, where it makes sense, a setter.
#include <iostream>
#include <string>
class Vehicle {
public:
explicit Vehicle(const std::string& reg) : registration_(reg), mileage_(0) {}
const std::string& registration() const {
return registration_;
}
int mileage() const {
return mileage_;
}
void add_mileage(int miles) {
if (miles > 0) {
mileage_ += miles;
}
}
private:
std::string registration_;
int mileage_;
};
int main() {
Vehicle van("VN-4471");
van.add_mileage(1200);
van.add_mileage(-500); // ignored: a negative trip is not possible
std::cout << van.registration() << ": " << van.mileage() << " miles\n";
return 0;
}The trailing underscore on the member name is a widespread convention that keeps it distinct from the accessor of the same name.
VN-4471: 1200 milesNotice that add_mileage is better than a setter, because it can enforce the rule that the mileage only ever increases. A setter would have to accept the caller's judgement, and the caller would have to know the rule.
protected is for inheritance
The protected members are private to everybody except the class itself and its derived classes. They exist so that a derived class can work with the internals of the base class without making them public to the world.
#include <iostream>
#include <string>
class Vehicle {
public:
explicit Vehicle(const std::string& reg) : registration_(reg) {}
const std::string& registration() const {
return registration_;
}
protected:
void set_registration(const std::string& reg) {
registration_ = reg;
}
private:
std::string registration_;
};
class FleetVehicle : public Vehicle {
public:
FleetVehicle(const std::string& reg, int seats)
: Vehicle(reg), seat_count_(seats) {}
void reassign(const std::string& reg) {
set_registration(reg); // allowed: protected
}
int seats() const {
return seat_count_;
}
private:
int seat_count_;
};
int main() {
FleetVehicle shuttle("SH-22", 12);
shuttle.reassign("SH-23");
std::cout << shuttle.registration() << " with " << shuttle.seats() << " seats\n";
return 0;
}The output confirms that the derived class could reach the protected setter.
SH-23 with 12 seatsAnd protected is the weakest form of encapsulation and the easiest one to overuse. Many style guides now recommend avoiding it and using public member functions instead, because a protected member is still part of the contract of the class for every future subclass.
Encapsulation is what makes refactoring possible
The practical payoff is that a private member can be changed freely. If the odometer were stored as an int and you later need it as a long long because a vehicle passes a million miles, then you can change it as long as the accessors keep the same signatures. Every caller keeps working.
If the member were public then that change would break every caller, and you would have no way of stopping people from depending on the old layout.
Quick reference
- A class defaults to private and a struct defaults to public.
publicmeans that anybody may use it,privatemeans only this class, andprotectedmeans this class and its derived classes.- A private member with public accessors lets you change the implementation later.
- Prefer a method such as
add_mileageover a setter when the class can enforce a rule. protectedis a weak form of encapsulation, so prefer the public member functions.- Encapsulation is what makes the refactoring safe.
Try it yourself: write a Vehicle class with a public mileage field, and then change it to a private field with accessors and update your callers. Next, add a rule that the mileage can never decrease, and enforce it inside the class. Finally, write a derived class and use a protected member from it, and then try the same access from outside the class so that you can see the compiler refuse.