In C++, there are three different types of access specifiers:
Public: Public members are accessible from anywhere, both inside and outside of the class. Any function or object can access public members of a class.
Protected: Protected members are accessible from within the class and any derived classes. Outside of the class hierarchy, protected members are not accessible.
Private: Private members are accessible only within the class. They cannot be accessed from outside the class or by derived classes.
Here's an example that demonstrates the use of access specifiers:
c++class MyClass {
public:
int publicMember; // Public member variable
void publicMethod(); // Public member function
protected:
int protectedMember; // Protected member variable
void protectedMethod(); // Protected member function
private:
int privateMember; // Private member variable
void privateMethod(); // Private member function
};
void MyClass::publicMethod() {
publicMember = 1; // Accessible
protectedMember = 2; // Accessible
privateMember = 3; // Accessible
}
void MyClass::protectedMethod() {
publicMember = 1; // Accessible
protectedMember = 2; // Accessible
privateMember = 3; // Accessible
}
void MyClass::privateMethod() {
publicMember = 1; // Accessible
protectedMember = 2; // Accessible
privateMember = 3; // Accessible
}
int main() {
MyClass obj;
obj.publicMember = 1; // Accessible
obj.publicMethod(); // Accessible
// obj.protectedMember = 2; // Not accessible
// obj.protectedMethod(); // Not accessible
// obj.privateMember = 3; // Not accessible
// obj.privateMethod(); // Not accessible
return 0;
}
In this example, we have a class called MyClass
with public, protected, and private member variables and member functions. The publicMethod()
function can access all members, regardless of their access specifier. The protectedMethod()
and privateMethod()
functions can also access all members, but only from within the class. Finally, the main()
function can access the public members and public method of a MyClass
object, but not the protected or private members or methods.
Comments
Post a Comment