An access specifier is used to implement the principle of information hiding. This principle states that irrelevant and sensitive information should be kept hidden, as much as possible, outside of a class.
The three access specifiers in C++, in ascending order of accessibility, are:
private
All private
variables and functions can only be accessed from inside the class or friend class. When no specifier is written, the members in a class are considered private
by default.
class A{
private:
int x;
void foo(){
cout << "foo() executes";
// Increment private variable x from inside class:
x++;
}
};
int main(){
A obj;
// Executing private function foo() gives error:
obj.foo();
}
protected
The protected
members of a class are only accessible within that class and its child classes.
public
public
members can be accessed from anywhere outside the class. They provide an interface for interacting with an object of the class. A common example is a constructor that is declared public
so that an object of that class can be created.
class A{
private:
int x;
protected:
void foo(){
cout << "foo() executes";
// Increment private variable x from inside class:
x++;
}
};
class B: public A{
public:
B(){
// Execute foo() from inside a child class:
foo();
}
};
int main(){
A obj;
// Executing protected function foo() gives error:
obj.foo();
// Public constructor calls foo():
B obj;
}
Free Resources