Private and Protected Members in C++


A class in C++ has public, private and protected sections which contain the corresponding class members.

The private data members cannot be accessed from outside the class. They can only be accessed by class or friend functions. All the class members are private by default.

The protected members in a class are similar to private members but they can be accessed by derived classes or child classes while private members cannot.

A program that demonstrates private and protected members in a class is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
class Base {
   public :
   int a = 8;
   protected :
   int b = 10;
   private :
   int c = 20;
};
class Derived : public Base {
   public :
   void func() {
      cout << "The value of a : " << a;
      cout << "\nThe value of b : " << b;
   }
};
int main() {
   Derived obj;
   obj.func();
   return 0;
}

Output

The output of the above program is as follows.

The value of a : 8
The value of b : 10

Now, let us understand the above program.

In the class Base, the data members are a, b and c which are public, protected and private respectively. The code snippet for this is given as follows.

class Base {
   public :
   int a = 8;
   protected :
   int b = 10;
   private :
   int c = 20;
};

The class Derived inherits the class Base. The function func() prints the values of a and b. It cannot print the value of c as that is private to class Base and cannot be accessed in class Derived. The code snippet for this is given as follows.

class Derived : public Base {
   public :
   void func() {
      cout << "The value of a : " << a;
      cout << "\nThe value of b : " << b;
   }
};

In the function main(), the object obj of class Derived is created. Then the function func() is called. The code snippet for this is given as follows.

int main() {
   Derived obj;
   obj.func();
   return 0;
}

Updated on: 26-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements