Skip to content
Related Articles

Related Articles

Improve Article

Public vs Protected in C++ with Examples

  • Last Updated : 29 Oct, 2019

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

PublicProtected
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.
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :