Loading....
Coupon Accepted Successfully!

 

The private keyword

The private keyword is used to prevent direct access of member variables or function by the object. The class by default produces this effect.

The structure variables by default are public. To prevent member variables and functions of struct from direct access, the private keyword is used. The syntax of private keyword is same as public. The private keyword is terminated with a colon. Consider the following example.
 


As soon as the above program is compiled, the compiler will display the following error message:

 

‘item::codeno’ is not accessible

‘item::prize’ is not accessible

‘item::qty’ is not accessible

‘item::codeno’ is not accessible

‘item::prize’ is not accessible


From the above discussion, we noticed that by default (without applying public or private keyword) the class members are private (not accessible) whereas the struct members are public (accessible).


The private members are not accessible by the object directly. Then the question is how will they be accessed? To access the private members of a class, member functions of the same class are used. The member function must be declared in the class in public section. A program on accessing private members is given in the forthcoming sections. Through the public member function, an object can access the private members.





Test Your Skills Now!
Take a Quiz now
Reviewer Name