Open In App

Public vs Protected in C++ with Examples

Public

All the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.



Example:




// C++ program to demonstrate public
// access modifier
  
#include <iostream>
using namespace std;
  
// class definition
class Circle {
public:
    double radius;
  
    double compute_area()
    {
        return 3.14 * radius * radius;
    }
};
  
// main function
int main()
{
    Circle obj;
  
    // accessing public data member outside class
    obj.radius = 5.5;
  
    cout << "Radius is: " << obj.radius << "\n";
    cout << "Area is: " << obj.compute_area();
    return 0;
}

Output:
Radius is: 5.5
Area is: 94.985

In the above program, the data member radius is public so we are allowed to access it outside the class.



Protected

Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.
Example:




// C++ program to demonstrate
// protected access modifier
#include <bits/stdc++.h>
using namespace std;
  
// base class
class Parent {
    // protected data members
protected:
    int id_protected;
};
  
// sub class or derived class
class Child : public Parent {
  
public:
    void setId(int id)
    {
  
        // Child class is able to access the inherited
        // protected data members of base class
  
        id_protected = id;
    }
  
    void displayId()
    {
        cout << "id_protected is: " << id_protected << endl;
    }
};
  
// main function
int main()
{
  
    Child obj1;
  
    // member function of the derived class can
    // access the protected data members of the base class
  
    obj1.setId(81);
    obj1.displayId();
    return 0;
}

Difference between Public and Protected

Public Protected
All the class members declared under public will be available to everyone. Protected access modifier is similar to that of private access modifiers.
The data members and member functions declared public can be accessed by other classes too. The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.

Article Tags :