Access Specifiers
C++ has three access specifiers — public, private, and protected — that control which code is allowed to see a class's members. They can appear as many times as you like inside a class body; each one applies to every member declared after it, until the next specifier or the end of the class.
Specifier | Accessible from the class itself | Accessible from derived classes | Accessible from outside code |
|---|---|---|---|
| Yes | Yes | Yes |
| Yes | Yes | No |
| Yes | No | No |
All three specifiers in one class
class Example {
public:
int pub = 1; // visible everywhere
protected:
int prot = 2; // visible in Example and any class derived from it
private:
int priv = 3; // visible only inside Example's own member functions
};Default access: struct vs. class (recap)
As covered on the Classes & Objects page, class members default to private and struct members default to public if you don't write a specifier at all — that is the only structural difference between the two keywords in C++.
Default access without an explicit specifier
class A {
int x; // private by default
};
struct B {
int x; // public by default
};A compile error from outside access
Trying to touch a private member from outside the class — even from main() — is a compile-time error, not a runtime one. This is exactly the mechanism that makes encapsulation enforceable rather than just a convention.
Accessing a private member from outside fails to compile
class Rectangle {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const { return width * height; }
};
int main() {
Rectangle r(3.0, 4.0);
r.area(); // OK — area() is public
// r.width = 10.0; // Error: 'width' is a private member of 'Rectangle'
}The friend escape hatch
Occasionally a specific outside function or class legitimately needs access to another class's private members — the most common example is overloading operator<< for printing. C++ provides the friend keyword for exactly this narrow purpose: a class can explicitly grant access to a chosen function or class, without opening its internals up to everyone. The Friend Functions & Classes page later in this section covers the syntax and when (and when not) to reach for it.
What's next
protectedbecomes meaningful once you introduce a base class and derived classes — see Inheritance, next.