C++ Encapsulation
In object-oriented programming, encapsulation, which refers to the practise of concealing an object’s internal characteristics and offering a public interface to access and modify its data, is a crucial notion. The goal is to secure data from direct access and alteration by outside code, hence enhancing programme safety and maintainability. Access modifiers, such as public, private, and protected, are used to limit the visibility of class members in order to accomplish encapsulation.
A class is used in C++ to group together data and behaviour into a single entity. The properties and methods of the class are specified in the class declaration, and the visibility of those members is determined by the access modifiers. Class members are often private by default, which limits access to the class itself. On the other hand, external code can access public members.
Example:
#include <iostream>
using namespace std;
class Person {
public:
void setName(string name) {
this->name = name;
}
string getName() const {
return name;
}
private:
string name;
};
int main() {
Person p;
p.setName("John Doe");
cout << "Name: " << p.getName() << endl;
return 0;
}
Output:
Name: John Doe
In this illustration, the person’s name is contained in a class called Person. The names can be set and retrieved using the setName() and getName() methods, respectively. Since the name data member is marked as private, access to it directly from outside the class is prohibited. Instead, only the class’s public methods can be used to access it.
We protect the name data member from unintentional modification by outside code by enclosing it. This enhances the programme’s dependability and safety. Encapsulation also makes it simpler to modify a class’s internal implementation without changing its external interface. This enables us to increase the code’s effectiveness and maintainability.