-
Hajipur, Bihar, 844101
Encapsulation is one of the four main pillars of Object-Oriented Programming (OOP) in C++. It refers to the process of binding data and the functions that operate on that data into a single unit, known as a class.
In simpler terms, encapsulation means keeping the data (variables) of a class private and allowing access to it only through public methods. This ensures that the data cannot be changed accidentally or used incorrectly by external code.
Encapsulation helps in data protection, code security, and better maintainability of the program.
In C++, encapsulation is mainly implemented using access specifiers:
private – Members are accessible only within the same class.
public – Members are accessible from anywhere in the program.
protected – Members are accessible within the class and derived classes.
By making class data members private and providing public getter and setter methods, you can control how the data is accessed and modified.
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
public:
void setName(string n) {
name = n;
}
void setAge(int a) {
if (a > 0)
age = a;
else
cout << "Invalid age" << endl;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Student s1;
s1.setName("Ananya");
s1.setAge(20);
s1.display();
return 0;
}
name and age are private data members.
You cannot access them directly from outside the class.
The setName() and setAge() functions are public methods that control how data is modified.
This ensures safety and prevents invalid data from being stored.
Encapsulation is not just about hiding data — it provides several key benefits:
Data Security: Prevents unwanted modification of sensitive data.
Code Reusability: Encapsulated classes can be reused across projects.
Flexibility: You can change internal implementation without affecting other parts of the program.
Readability: Code becomes organized and easier to understand.
Maintenance: Modifying one part of the code doesn’t break other parts since data access is controlled.
Think of encapsulation like a mobile phone:
You can make calls or send messages (public functions).
But you cannot directly access the phone’s internal chip or hardware (private data).
Similarly, in C++, classes hide complex logic behind simple public interfaces.
A common way to implement encapsulation is by using getter and setter functions.
#include <iostream>
using namespace std;
class Employee {
private:
int empId;
double salary;
public:
void setEmpId(int id) {
empId = id;
}
int getEmpId() {
return empId;
}
void setSalary(double s) {
if (s >= 0)
salary = s;
else
cout << "Invalid salary" << endl;
}
double getSalary() {
return salary;
}
};
int main() {
Employee e1;
e1.setEmpId(101);
e1.setSalary(50000);
cout << "Employee ID: " << e1.getEmpId() << endl;
cout << "Salary: " << e1.getSalary() << endl;
return 0;
}
The private members empId and salary can’t be accessed directly.
Public functions setEmpId(), setSalary(), getEmpId(), and getSalary() are used to interact with these values safely.
Validation checks in setters make the code more reliable.
Constructors can also help encapsulate data by ensuring it’s initialized properly at the time of object creation.
#include <iostream>
using namespace std;
class Car {
private:
string brand;
int year;
public:
Car(string b, int y) {
brand = b;
year = y;
}
void showData() {
cout << "Brand: " << brand << endl;
cout << "Year: " << year << endl;
}
};
int main() {
Car c1("Honda", 2023);
c1.showData();
return 0;
}
Here, the constructor ensures both private data members (brand and year) are always properly initialized.
These two terms are closely related but slightly different:
| Concept | Description |
|---|---|
| Encapsulation | Wrapping data and functions together into a class. |
| Data Hiding | Restricting access to internal data using access specifiers. |
Encapsulation is the broader concept, while data hiding is one of its key goals.
Use encapsulation when:
You need to protect data from direct modification.
You want to control how data is accessed or validated.
You plan to scale your program with multiple classes interacting safely.
You want cleaner, modular, and maintainable code.
Exposing class members as public unnecessarily.
Not adding validation checks in setters.
Mixing unrelated functionalities inside one class.
Forgetting to initialize private data using constructors or setters.
Encapsulation in C++ is all about protecting and managing access to your data. It hides the internal state of objects and provides public methods for safe interaction.
By applying encapsulation, you make your code more organized, secure, and easy to maintain. It’s one of the most powerful principles that make C++ a true object-oriented language.
Create a class Person with private data members name and age. Use public setter and getter methods to set and display the values.
Write a C++ program that demonstrates encapsulation using a class BankAccount where balance can only be accessed and modified through deposit and withdraw functions.
Define a class Student that encapsulates roll number and marks as private data. Provide methods to assign and display them.
Write a program that uses encapsulation to validate user input when setting a Product price. The price should not be negative.
Create a class Rectangle with private data members length and width. Provide methods to calculate and display the area and perimeter.
Implement a class Car where the speed can be changed only through methods accelerate() and brake(). Speed should never go below zero.
Write a C++ program to demonstrate how encapsulation hides internal logic inside a class TemperatureConverter that converts Celsius to Fahrenheit.
Define a class Book with private members title and author, and public methods to set and get their values. Display details using an object.
Create a class Employee with a private salary variable. Allow salary updates only if the amount is greater than zero using encapsulated methods.
Write a program that demonstrates encapsulation with a class Account that allows checking the balance through a getter but doesn’t allow direct modification.