In C++, visibility modes control the accessibility of class members (data members and member functions) from other classes. This is crucial for encapsulation and information hiding. C++ provides three visibility modes:
1. Public:
Public members are accessible from anywhere, including within the class, derived classes, and other classes.
They are often used for data members that need to be accessed and modified by other parts of the program.
Example:
#include <iostream>
using namespace std;
class PublicClass {
public:
int public_var;
void public_function() {
cout << "Public function" << endl;
}
};
int main() {
PublicClass obj;
obj.public_var = 10;
obj.public_function();
return 0;
}
2. Private:
Private members are only accessible within the class itself.
They are used to hide implementation details and protect data integrity.
Example:
#include <iostream>
using namespace std;
class PrivateClass {
private:
int private_var;
public:
void setPrivateVar(int value) {
private_var = value;
}
int getPrivateVar() {
return private_var;
}
};
int main() {
PrivateClass obj;
obj.setPrivateVar(20);
cout << obj.getPrivateVar() << endl;
return 0;
}
3. Protected:
Protected members are accessible within the class itself and its derived classes.
They are often used to create base classes that provide a foundation for derived classes.
Example:
#include <iostream>
using namespace std;
class ProtectedClass {
protected:
int protected_var;
public:
void setProtectedVar(int value) {
protected_var = value;
}
};
class DerivedClass : public ProtectedClass {
public:
void printProtectedVar() {
cout << protected_var << endl;
}
};
int main() {
DerivedClass obj;
obj.setProtectedVar(30);
obj.printProtectedVar();
return 0;
}
By understanding and effectively using these visibility modes, you can create well-structured, maintainable, and secure C++ programs. Remember to carefully consider the accessibility of your class members to ensure proper encapsulation and information hiding.
コメント