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.
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:
#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 Public and Private
Public
Private
All the class members declared under public will be available to everyone.
The class members declared as private can be accessed only by the functions inside the class.
The data members and member functions declared public can be accessed by other classes too.
Only the member functions or the friend functions are allowed to access the private data members of a class.
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.
They are not allowed to be accessed directly by any object or function outside the class.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
15 Oct, 2019
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...