C++ Encapsulation: Access Modifiers Explained
C++ class encapsulation is achieved through access control modifiers, mainly including public, protected, and private. The public modifier is used to declare a class’s public members, which can be accessed from outside the class; the private modifier is used to declare a class’s private members, which can only be accessed within the class; the protected modifier is used to declare a class’s protected members, which can be accessed by derived classes.
Here is a simple example showcasing how to implement a class with private attributes and public methods:
class Person {
private:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
void setName(string n) {
name = n;
}
string getName() {
return name;
}
void setAge(int a) {
age = a;
}
int getAge() {
return age;
}
};
In the example above, name and age are declared as private attributes, only accessible within the Person class. setName, getName, setAge, and getAge are declared as public methods, which can be accessed externally. This achieves encapsulation of the class attributes, where external access and manipulation of the attributes can only be done through public methods, ensuring data security and integrity.