Difference between Private and Protected in C++ with Example
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:
CPP
#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;
}
|
Output:
id_protected is: 81
Private
The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
Example:
CPP
#include <iostream>
using namespace std;
class Circle {
private :
double radius;
public :
void compute_area( double r)
{
radius = r;
double area = 3.14 * radius * radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
}
};
int main()
{
Circle obj;
obj.compute_area(1.5);
return 0;
}
|
Output:
Radius is: 1.5
Area is: 7.065
Difference between Private and Protected
Private |
Protected |
|
|
The class members declared as private can be accessed only by the functions inside the class. |
Protected access modifier is similar to that of private access modifiers. |
Private members keep implementation details in a program. |
Protected members enhanced access for derived classes. |
Only the member functions or the friend functions are allowed to access the private data members of a class. |
The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class. |
Private member are not inherited in class. |
Protected member are inherited in class. |
Last Updated :
03 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...