Loading lessons...
Access Specifiers
Access Specifiers
An access specifier is a keyword inside a class that controls who can use the members declared after it. There are three: public, private, and protected.
Setting up sections
Sections are introduced with a semicolon followed by the keyword and a colon:
class Account {
public:
double balance; // reachable from outside
private:
int pin; // hidden from outside
protected:
int owner; // reachable by derived classes
};
A section stays in force until the next specifier.
What each keyword means
- public: members can be used from anywhere the object is visible.
- private: members are hidden from outside the class; only the class's own code (and friends) can touch them.
- protected: like private, but derived classes can also reach them.
The default is private
In a class, members are private by default. The class author must deliberately open them up with public:. That keeps the class's internals safe by default.
TL;DR
- The three access specifiers are
public,private, andprotected. - In a class the default is private.
- A section stays active until the next specifier.
publicopens,privatehides,protectedshares with derived classes only.