4.5) Access specifiers C++
Access specifiers are keywords used in C++ to control the visibility and accessibility of class members (attributes and methods) from different parts of the program. They define the level of encapsulation and data hiding within a class.
C++ supports three access specifiers:
- public,
- private, and
- protected.
Here’s a detailed explanation of access specifiers with code examples:
Table of Contents
1. public Access Specifier
Members declared as public are accessible from anywhere in the program. They can be accessed directly using object instances.
class MyClass {
public:
int publicVar;
void publicMethod() {
// Public method code
}
};
int main() {
MyClass obj;
obj.publicVar = 42;
obj.publicMethod();
return 0;
}
2. private Access Specifier
Members declared as private are only accessible within the class itself. They cannot be accessed directly from outside the class.
class MyClass {
private:
int privateVar;
public:
void setPrivateVar(int value) {
privateVar = value;
}
int getPrivateVar() {
return privateVar;
}
};
int main() {
MyClass obj;
obj.setPrivateVar(42);
// obj.privateVar = 42; // This will result in an error
int value = obj.getPrivateVar();
return 0;
}
3. protected Access Specifier
Members declared as protected are similar to private, but they can be accessed by derived classes. They are used in inheritance scenarios to provide controlled access to derived classes.
class Base {
protected:
int protectedVar;
};
class Derived : public Base {
public:
void setProtectedVar(int value) {
protectedVar = value;
}
int getProtectedVar() {
return protectedVar;
}
};
int main() {
Derived obj;
obj.setProtectedVar(42);
// obj.protectedVar = 42; // This will result in an error
int value = obj.getProtectedVar();
return 0;
}
Access Specifiers and Inheritance
Access specifiers also play a role in inheritance. The visibility of inherited members is affected by the access specifier used in the base class:
- public: The inherited members retain their original access levels.
- protected: The inherited members become
protected
in the derived class. - private: The inherited members are not accessible in the derived class.
class Base {
public:
int publicVar;
void publicMethod() {}
protected:
int protectedVar;
void protectedMethod() {}
private:
int privateVar;
void privateMethod() {}
};
class Derived : public Base {
public:
void useInheritedMembers() {
publicVar = 1; // OK
protectedVar = 2; // OK
// privateVar = 3; // Error
publicMethod(); // OK
protectedMethod(); // OK
// privateMethod(); // Error
}
};
Access specifiers provide control over the visibility and accessibility of class members, contributing to the principles of encapsulation and data hiding in object-oriented programming. By selecting the appropriate access specifier, you can enforce proper encapsulation and limit access to internal details, making your code more secure and maintainable.