C++ Encapsulation
Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP) and refers to the practice of keeping the internal workings of an object hidden from the outside world. This means that the data and behavior of an object are packaged together in a single unit, and only the object's public methods and properties are visible to other parts of the program. Encapsulation helps to ensure that the data and behavior of an object remain consistent, even as the program evolves over time.
Let's consider an example of encapsulation in C++ where we create a class called "Employee". This class has two private members, "name" and "age", and two public methods, "getName" and "setName". The "getName" method returns the value of the "name" member and the "setName" method sets the value of the "name" member.
1#include <iostream> 2#include <string> 3using namespace std; 4 5class Employee 6{ 7 private: 8 string name; 9 int age; 10 public: 11 void setName(string n) 12 { 13 name = n; 14 } 15 string getName() 16 { 17 return name; 18 } 19}; 20 21int main() 22{ 23 Employee emp1; 24 emp1.setName("William Max"); 25 cout << "Employee Name: " << emp1.getName() << endl; 26 return 0; 27}
Output:
Employee Name: William Max
In this example, the data members of the "Employee" class are private, and can only be accessed through the public methods, "getName" and "setName". This helps to ensure that the data is protected from being accessed or modified directly from outside the class. The internal workings of the class are hidden, and the class can only be interacted with through its public interface. This encapsulation makes it easier to modify the class without affecting other parts of the program, and makes the code more robust and less prone to errors.