Public, Private, Protected - EduardoMSU/OOP-2143 GitHub Wiki
In object-oriented programming (OOP), access modifiers are used to define the visibility or accessibility of members (variables and methods) of a class. The primary access modifiers in most programming languages (including C++) are public, private, and protected.
Access Modifier | Description | Access Level |
---|---|---|
public | Members declared as public are accessible from anywhere, both inside and outside the class. | Open to everyone |
private | Members declared as private can only be accessed from within the class itself. They cannot be accessed from outside the class. | Restricted to the class only |
protected | Members declared as protected are accessible within the class and by derived (child) classes. However, they are not accessible from outside the class. | Accessible in derived classes |
The public access modifier allows members (variables and methods) to be accessed from anywhere, meaning they can be accessed by code outside of the class, such as in the main()
function or other objects.
#include <iostream>
using namespace std;
class MyClass {
public:
int x; // Public variable
// Public method
void display() {
cout << "Value of x: " << x << endl;
}
};
int main() {
MyClass obj;
obj.x = 10; // Direct access to public variable
obj.display(); // Call to public method
return 0;
}