Difference between private, public, and protected modifiers in C++

C++Server Side ProgrammingProgramming

Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled access modifiers − public, private, and protected sections within the class body.

The default access for members and classes is private.

Example

class Base {
public:
   // public members go here
protected:

   // protected members go here
private:
   // private members go here
};

A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member.

A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.


raja
Published on 28-Feb-2018 15:56:04
Advertisements