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:
#include <iostream>
using namespace std;
class Circle {
public :
double radius;
double compute_area()
{
return 3.14 * radius * radius;
}
};
int main()
{
Circle obj;
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:
#include <bits/stdc++.h>
using namespace std;
class Parent {
protected :
int id_protected;
};
class Child : public Parent {
public :
void setId( int id)
{
id_protected = id;
}
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};
int main()
{
Child obj1;
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. |
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...