C++ Access Specifiers
Access specifiers control who is allowed to touch the members of a class. They are one of the most important tools C++ gives you for building safe, well-organized objects, because they decide which parts of a class are open to the outside world and which parts are kept private inside.
What are access specifiers?
In C++ there are three access specifiers: public, private, and protected. You write them inside a class followed by a colon, and every member declared after them takes on that access level until another specifier appears. Think of them as labels that group your members into different levels of visibility.
- public: members can be reached from anywhere the object is visible, including from outside the class.
- private: members can only be reached from inside the class itself (its own methods).
- protected: like private, but also reachable from classes that inherit from this class.
Public members can be accessed directly
#include <iostream>
using namespace std;
class Car {
public:
string brand; // accessible from anywhere
int speed;
};
int main() {
Car myCar;
myCar.brand = "Toyota"; // works: brand is public
myCar.speed = 120;
cout << myCar.brand << " at " << myCar.speed << " km/h";
return 0;
}Private members are hidden from the outside
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // hidden from outside code
public:
void setBalance(double amount) {
balance = amount; // allowed: same class
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount acc;
acc.setBalance(500.0); // works through a public method
// acc.balance = 999; // ERROR: balance is private
cout << acc.getBalance(); // prints 500
return 0;
}In the example above, balance cannot be changed directly from main(). The only way in is through the public methods setBalance() and getBalance(). This lets the class stay in control of its own data, which is exactly the point of access specifiers.
Exercise: C++ Access Specifiers
Which access specifier lets a member be reached from anywhere the object is visible, even outside the class?