In the concept of C++ class objects, there are three access modifiers: 1) private, 2) protected and 3) public. They are used based on their properties. Here, we will understand what are private and protected members and what are the differences between them?
Private members
Private members are declared with the keyword private followed by the colon (:) character in the class and they are accessible within the class only in which they are declared. Private members cannot be accessed outside of the class.
Private members can be data members (variables) and member functions (functions) and both can be accessed within the same class, they can be used within the private/public member functions of the same class.
Consider the below example, it contains two private members name and city and they are being used within the public member functions getPerson() and dispPerson().
Protected members
Protected members are declared with the keyword protected followed by the colon (:) character in the class and they are accessible within the class in which they are declared and also accessible in the derived or subclass. Protected members are used in the concept of inheritance. Just like Private Members Protected members cannot be accessed outside of the class (except in the derived class).
Protected members can be data members (variables) and member functions (functions) and both can be accessed within the same class and derived or subclass or child class.
Consider the below example, there are two classes person which is a base class and person2 which a derived class, person class contains two private members name and city, one protected member roll_no and private members are being used within the public member functions getPerson() and dispPerson().
In the person1 class, there is one private member city and three public member functions set_roll_no() – which is using to set the value of roll_no that is a protected member in person class, getPerson1() – which is calling the getPerson() member function of person class and also getting the input of city. Similarly, dispPerson1() – which is calling the dispPerson() member function and also printing the value of roll_no and city.
Difference between private and protected members