encapsulation and abstraction in cpp
encapsulation abstraction in cpp
Introduction
Encapsulation and abstraction are two important principles of Object-Oriented Programming (OOP) in C++. They both help in designing secure, maintainable, and modular code, but they serve different purposes.
Encapsulation is the process of bundling data (variables) and methods (functions) that operate on that data into a single unit, called a class. It also involves restricting direct access to some components of an object to protect data integrity.
Key Points:
Achieved using classes
Uses access specifiers (private
, protected
, public
)
Helps with data hiding and security
#include <iostream>
using namespace std;
class Developer {
private:
double salary; // private data
public:
string name;
void setSalary(double s) {
salary = s; // controlled access
}
double getSalary() {
return salary;
}
};
int main() {
Developer dev;
dev.name = "Alice";
dev.setSalary(7000);
cout << dev.name << " earns $" << dev.getSalary() << " per month." << endl;
return 0;
}
Output:
Alice earns $7000 per month.
Benefits:
Protects data from unauthorized access
Makes code maintainable and modular
Abstraction means showing only essential details and hiding the implementation from the user. It focuses on what an object does rather than how it does it.
Key Points:
Achieved using abstract classes (with pure virtual functions)
Hides complex internal logic
Provides a clear interface to the user
#include <iostream>
using namespace std;
class Employee {
public:
virtual void work() = 0; // pure virtual function
virtual ~Employee() {}
};
class Developer : public Employee {
public:
void work() override {
cout << "Developer is writing code." << endl;
}
};
class Manager : public Employee {
public:
void work() override {
cout << "Manager is planning projects." << endl;
}
};
int main() {
Employee* e1 = new Developer();
Employee* e2 = new Manager();
e1->work();
e2->work();
delete e1;
delete e2;
return 0;
}
Output:
Developer is writing code.
Manager is planning projects.
Benefits:
Hides complex implementation
Makes systems easier to use and modify
Promotes modular design
Feature | Encapsulation | Abstraction |
---|---|---|
Purpose | Protects data | Hides implementation details |
Achieved by | Classes, access specifiers | Abstract classes, interfaces |
Focus | How data is accessed | What actions are performed |
Data visibility | Data is hidden and secured | Only essential details are shown |
Encapsulation and abstraction are complementary:
Encapsulation protects the data.
Abstraction hides implementation details.
Together, they make your C++ code more secure, modular, and maintainable.