Encapsulation is the concept of bundling the data (variables) and the methods (functions) that operate on the data into a single unit called a class. It also restricts access to some of the object’s components, making it possible to prevent unintended interference and misuse by controlling how the data is accessed or modified.
Data is hidden and can only be accessed or modified using special functions (like getter and setter).
Example:
#include <iostream>
using namespace std;
class Employee {
private:
string name; // private data member
public:
// Setter method to set the name
void setName(string n) {
name = n;
}
// Getter method to get the name
string getName() {
return name;
}
};
int main() {
Employee emp;
// Set the name using the setter method
emp.setName("John");
// Get the name using the getter method
cout << "Name: " << emp.getName() << endl;
return 0;
}
Explanation:
- name is a private variable, meaning it cannot be accessed directly outside the class.
- To modify or read name, we use public methods setName() and getName(). These methods control how the data is accessed or changed.
- This ensures that the internal state of the object (name) is protected and cannot be directly altered by code outside the class.
Output:
Benefits of Encapsulation
1. Improved security and control over data.
2. Code maintainability: Changes to the internal implementation of a class can be made without affecting external code that uses the class, as long as the interface (public methods) remains the same.
3. Prevents unauthorized access and modification of data.
4. Makes the code easier to understand and maintain by keeping implementation details hidden.
C++ Encapsulation – Interview Questions
Q 1: What is encapsulation?
Ans: Binding data and methods together in a class.
Q 2: Which access modifier supports encapsulation most?
Ans: private.
Q 3: How is encapsulation implemented?
Ans: Using private data members and public methods.
Q 4: What is data hiding?
Ans: Restricting direct access to class data.
Q 5: Advantage of encapsulation?
Ans: Improves security and maintainability.
C++ Encapsulation – Objective Questions (MCQs)
Q1. What is encapsulation in C++?
Q2. Which of the following is a key feature of encapsulation?
Q3. How can data members of a class be hidden from outside access?
Q4. Which of the following allows controlled access to private data members?
Q5. Why is encapsulation important in C++?