/* */ Click to Join Live Class with Shankar sir Call 9798158723

What is Protected Members Function in C++ ?


In the protected visibility mode, when we inherit a child class from the parent class, then all the members of the base class will become the protected members of the derived class.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.

Q.) Example of Protected Members Function in C++ .
    
 

#include < iostream>
using namespace std;

class Base {
  private:
    int pvt = 1;

  protected:
    int prot = 2;

   public:
    int pub = 3;

    // function to access private member
    int getPVT() {
      return pvt;
    }
};

class ProtectedDerived : protected Base {
  public:
    // function to access protected member from Base
    int getProt() {
      return prot;
    }

    // function to access public member from Base
    int getPub() {
      return pub;
    }
};

int main() {
  ProtectedDerived object1;
  cout << "Private cannot be accessed." << endl;
  cout << "Protected = " << object1.getProt() << endl;
  cout << "Public = " << object1.getPub() << endl;
  return 0;
}

Output
Private cannot be accessed.
Protected = 2
Public = 3