Contents

Encapsulation and Abstraction​

Encapsulation in C++

Encapsulation in C++ refers to the bundling of data and functions that operate on that data into a single unit or class. In Object-Oriented Programming (OOP), encapsulation plays a significant role in ensuring data protection by restricting direct access to an object’s attributes.

Real-Life Example of Encapsulation

Consider a company that has several departments, such as accounting, finance, and sales. Each department manages its own specific data:

  • The finance department handles all financial transactions and manages its own financial records.

  • The sales department is responsible for sales-related activities and keeps sales records.

If a finance department official needs to access sales data for a particular month, they cannot directly access it. Instead, they need to request the relevant data from someone in the sales department, maintaining controlled access to the information.

This exemplifies encapsulation: the sales department’s data and the methods to manage it are wrapped together, providing controlled access.

Key Properties of Encapsulation

1. Data Protection: Encapsulation safeguards an object’s internal state by keeping its data members private. External code can only interact with the data through public methods, which ensures that the data is manipulated securely and in a controlled manner.

2. Information Hiding: Encapsulation conceals the internal workings of a class, exposing only a public interface to the outside world. This abstraction simplifies the use of the class, as external code doesn’t need to understand the internal details, allowing those details to be changed without impacting other parts of the program.

Example 1: Simple Encapsulation

				
					#include <iostream>
using namespace std;

class Number {
private:
    int value;

public:
    void setValue(int input) {
        value = input;
    }

    int getHalf() {
        return value / 2;
    }
};

int main() {
    Number num;
    int n;
    cin >> n;
    num.setValue(n);
    cout << "Half of " << n << " is: " << num.getHalf() << endl;
    return 0;
}

				
			

In this example, the class Number encapsulates the data (the integer value) and provides a method to manipulate that data (calculate half of the number). The value member is private and can only be accessed or modified through the class’s public methods.

Features of Encapsulation
  • Functions inside the class must interact with the class’s member variables. This ensures that encapsulation is effective.
  • Encapsulation improves the readability, maintainability, and security of code by organizing related data and methods into a cohesive unit.
  • It also provides control over how data members are modified, promoting better data integrity.

Example 2: Person Class

				
					#include <iostream>
#include <string>
using namespace std;

class Person {
private:
    string name;
    int age;

public:
    Person(string n, int a) : name(n), age(a) {}

    void setName(string n) {
        name = n;
    }

    string getName() {
        return name;
    }

    void setAge(int a) {
        age = a;
    }

    int getAge() {
        return age;
    }
};

int main() {
    Person person("Alice", 25);

    cout << "Name: " << person.getName() << endl;
    cout << "Age: " << person.getAge() << endl;

    person.setName("Bob");
    person.setAge(30);

    cout << "Name: " << person.getName() << endl;
    cout << "Age: " << person.getAge() << endl;

    return 0;
}

				
			

Abstraction in C++

Data abstraction is one of the core principles of Object-Oriented Programming (OOP) in C++. It involves showcasing only the essential features and hiding unnecessary details. In simpler terms, abstraction means focusing on what an object does rather than how it performs that task.

Real-Life Example of Abstraction

Imagine a person driving a car. The driver knows that pressing the accelerator increases the speed, and pressing the brakes stops the car. However, the driver is unaware of the complex internal mechanisms that make this happen, such as how the engine works or how the brake system operates. This concept illustrates abstraction, where only necessary information is provided to the user, and the intricate details are concealed.

Types of Abstraction

1. Data Abstraction: This form of abstraction presents only the relevant information about data, leaving out unnecessary details.

2. Control Abstraction: This type of abstraction focuses on hiding the details of the implementation, exposing only the essential behavior.

Abstraction in C++

Abstraction can be achieved in C++ through classes, access specifiers, and even header files. Let’s explore these mechanisms:

Abstraction using Classes

In C++, classes allow us to group data members and functions, and we can control which members are accessible to the outside world. This is done through access specifiers such as public and private. A class can decide which data members and methods should be exposed to the external world while keeping the internal details hidden.

Abstraction through Header Files

Header files also provide a form of abstraction. For example, when using the pow() function from the math.h library to calculate the power of a number, we do not need to know the underlying logic that the function uses. We simply call pow() with the necessary parameters, and the result is returned.

Abstraction using Access Specifiers

Access specifiers are crucial for implementing abstraction in C++. They control the visibility of class members:

  • Public members can be accessed from anywhere in the code.
  • Private members can only be accessed from within the class itself. They are hidden from the outside world and can only be manipulated by class methods.

By using access specifiers, we can enforce data abstraction by hiding the internal details and exposing only the necessary parts of the class.

Example of Abstraction

				
					#include <iostream>
using namespace std;

class AbstractExample {
private:
    int length, width;

public:
    // Method to set values for private members
    void setDimensions(int l, int w) {
        length = l;
        width = w;
    }

    // Method to calculate and display the area
    void displayArea() {
        cout << "Area of the rectangle: " << length * width << endl;
    }
};

int main() {
    AbstractExample rect;
    rect.setDimensions(5, 10);
    rect.displayArea();
    return 0;
}

				
			

Output:

				
					Area of the rectangle: 50
				
			

Difference between Abstraction and Encapsulation in C++

Abstraction: In Object-Oriented Programming (OOP), abstraction refers to the process of selectively exposing only the necessary details of an object while ignoring the complexities and unnecessary information. Abstraction simplifies the user’s interaction with an object by providing only what is essential and hiding the implementation complexities. This leads to cleaner, more efficient code by focusing on what an object does rather than how it does it.

Example of Abstraction:

				
					#include <iostream>
using namespace std;

class Calculator {
private:
    int num1, num2, result;

public:
    void add(int x, int y) {
        num1 = x;
        num2 = y;
        result = num1 + num2;
        cout << "Sum is: " << result << endl;
    }
};

int main() {
    Calculator calc;
    calc.add(7, 3);
    return 0;
}

				
			

Output:

				
					Sum is: 10
				
			

Encapsulation:

Encapsulation refers to the process of bundling the data and methods that operate on the data within a single unit, typically a class. This approach protects the data from unauthorized access and modification by restricting access to the data members through access specifiers like private, protected, and public. Encapsulation also naturally leads to data abstraction.

Example of Encapsulation:

				
					#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;

public:
    void setBalance(double amount) {
        balance = amount;
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account;
    account.setBalance(1000.50);
    cout << "Current balance: " << account.getBalance() << endl;
    return 0;
}

				
			

Output:

				
					Current balance: 1000.5
				
			
Difference Between Abstraction and Encapsulation:
S.No.AbstractionEncapsulation
1.Abstraction focuses on exposing only the necessary information.Encapsulation focuses on grouping data and methods into a single unit.
2.Abstraction addresses problems at the design or interface level.Encapsulation addresses problems at the implementation level.
3.It hides unnecessary details to simplify the interface.It hides data to protect it from external access.
4.Achieved using abstract classes and interfaces.Achieved through access specifiers like private, protected, and public.
5.Implementation details are hidden by using abstract classes or interfaces.Data is hidden by using getters and setters to access or modify the data.
6.Objects performing abstraction may use encapsulation to hide complexities.Objects using encapsulation do not necessarily need to involve abstraction.