Accessing protected members in a C++ derived class


A class in C++ has public, private and protected sections which contain the corresponding class members. Protected members in a class are similar to private members as they cannot be accessed from outside the class. But they can be accessed by derived classes or child classes while private members cannot.

A program that demonstrates accessing protected data members in a derived class in C++ is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
class Base {
   protected :
   int num = 7;
};
class Derived : public Base {
   public :
   void func() {
      cout << "The value of num is: " << num;
   }
};
int main() {
   Derived obj;
   obj.func();
   return 0;
}

Output

The output of the above program is as follows.

The value of num is: 7

Now, let us understand the above program.

In the class Base, the data member is num which is protected. The class Derived inherits the class Base. The function func() prints the value of num. The code snippet for this is given as follows.

class Base {
   protected :
   int num = 7;
};
class Derived : public Base {
   public :
   void func() {
      cout << "The value of num is: " <<< num;
   }
};

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

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements