Use of Public Private and Protected access specifiers in C++?

(Last Updated On: February 26, 2019)

Answer: Use of public private and protected access specifiers in C++ is to control the access/visibility of member data and functions out of a class.

It all depends upon requirement when we design a class, what access level to fields and member functions, we want to provide in a class with the use of public private and protected specifiers.

use of public private and protected access specifiers

Use of private access specifier in C++:

Use private specifier for data and functions of a class that are not supposed to be exposed outside of a class.

As a good class design, a class should have all data members private in a class and class’s functions should use these member data.

If we have to provide access to data members of a class to another class or program e.g. main (), we should not make it public or protected, but we should provide it using an interface i.e. public methods to access from outside of a class.

 

In below C++ class, all member fields are private. Let’s say, we want to allow another class to set or get the value of sum, then we should have public method getSum() and setSum() etc.

 

 

All the internal functions of a class that is used in class itself and public exposer of internal functions not required, then make them private. Only make function public which is supposed to be accessed from outside of a class.

Use of Public access specifier in C++:

Expose only required member functions to out of a class. So, it can be accessed from anywhere from another class or program.

 

 

Use of Protected access specifier in C++:

Use protected specifier if you want to allow access of data and member functions to child class only in inheritance.

 

In below program, data member “sum” and displaySum() function are protected and only available to child class. If we call them in main() program, compiler will flash an error i.e. protected member can’t be accessed.

 

 

Also, use of public private and protected access specifiers in C++ is in inheritance hierarchy that is how we want to inherit the base class. For example

 

 

Use of public instead of private may lead you in great pain. How? Read hear another interview question what is issue on using C++ public access specifier in place of private.