Software Development Exam  >  Software Development Notes  >  DSA in C++  >  Encapsulation in C++

Encapsulation in C++ | DSA in C++ - Software Development PDF Download

Introduction

In the world of data structures and algorithms (DSA), encapsulation plays a crucial role in designing efficient and secure code. Encapsulation is a fundamental principle of object-oriented programming (OOP) that allows us to bundle data and methods into a single unit called a class. In this article, we will explore encapsulation in DSA using C++. We will cover the concept of encapsulation, its benefits, and provide multiple examples with simple code explanations and outputs.

What is Encapsulation?

Encapsulation is a concept in OOP that binds data and methods together within a class, hiding the internal details of the implementation from outside access. It promotes the idea of data hiding and provides a way to control access to class members.

Benefits of Encapsulation

Encapsulation offers several advantages, including:

  • Data Protection: By encapsulating data within a class, we can prevent direct access to it from outside the class. This ensures data integrity and protects it from unintended modifications.
  • Code Organization: Encapsulation allows us to group related data and methods together within a class. This improves code organization and makes it easier to understand and maintain.
  • Code Reusability: Encapsulation facilitates code reuse since classes can be used as building blocks in other parts of the program. This leads to modular and scalable code.
  • Flexibility: By encapsulating data, we can change the internal implementation of a class without affecting the rest of the program. This promotes code flexibility and reduces the risk of breaking existing code.

Example 1: Encapsulation in C++
Let's look at a simple example to understand encapsulation in action. Consider a class called 'Person' that encapsulates the name and age of an individual. We will define private data members and public member functions to access and modify the encapsulated data.

class Person {

private:

    string name;

    int age;

public:

    void setName(string newName) {

        name = newName;

    }

    

    void setAge(int newAge) {

        age = newAge;

    }

    

    string getName() {

        return name;

    }

    

    int getAge() {

        return age;

    }

};


int main() {

    Person person;

    person.setName("John Doe");

    person.setAge(25);

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

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

    return 0;

}

Output:

Name: John Doe

Age: 25

Explanation:
In the above example, the 'Person' class encapsulates the name and age as private data members. The public member functions 'setName', 'setAge', 'getName', and 'getAge' provide controlled access to these private members. We create an instance of the Person class named 'person' in the 'main' function and use the setter functions to set the name and age. Then, we use the getter functions to retrieve and display the encapsulated data.

Example 2: Encapsulation with Complex Data Structure
Encapsulation is not limited to primitive data types. It can be applied to complex data structures as well. Let's consider a class called 'Stack', which encapsulates the behavior of a stack data structure.

class Stack {

private:

    int arr[100];

    int top;

public:

    Stack() {

        top = -1;

    }

    

    bool isEmpty() {

        return (top == -1);

    }

    

    void push(int value) {

        if (top >= 99) {

            cout << "Stack overflow!" << endl;

            return;

        }

        arr[++top] = value;

    }

    

    void pop() {

        if (isEmpty()) {

            cout << "Stack underflow!" << endl;

            return;

        }

        top--;

    }

    

    int peek() {

        if (isEmpty()) {

            cout << "Stack is empty!" << endl;

            return -1;

        }

        return arr[top];

    }

};


int main() {

    Stack stack;

    stack.push(5);

    stack.push(10);

    stack.push(15);

    cout << "Top element: " << stack.peek() << endl;

    stack.pop();

    cout << "Top element: " << stack.peek() << endl;

    return 0;

}

Output:

Top element: 15

Top element: 10

Explanation:
In this example, the 'Stack' class encapsulates an array 'arr' and a top index 'top'. The private data members are hidden from direct access. Public member functions like 'push', 'pop', 'peek', and 'isEmpty' provide the necessary functionality to interact with the stack. The 'main' function demonstrates the usage of these functions by creating a 'Stack' instance named 'stack'. We push three elements onto the stack, peek at the top element, and then pop an element before peeking again.

Sample Problems

Here are some sample problems to further practice your understanding of encapsulation in DSA using C++:

Problem 1: Implement a class called 'Rectangle' that encapsulates the width and height of a rectangle. Provide member functions to calculate the area and perimeter of the rectangle.

class Rectangle {

private:

    double width;

    double height;

public:

    void setWidth(double newWidth) {

        width = newWidth;

    }

    

    void setHeight(double newHeight) {

        height = newHeight;

    }

    

    double getArea() {

        return width * height;

    }

    

    double getPerimeter() {

        return 2 * (width + height);

    }

};


int main() {

    Rectangle rectangle;

    rectangle.setWidth(5.0);

    rectangle.setHeight(3.0);

    cout << "Area: " << rectangle.getArea() << endl;

    cout << "Perimeter: " << rectangle.getPerimeter() << endl;

    return 0;

}

Output:

Area: 15

Perimeter: 16

Problem 2: Implement a class called 'BankAccount' that encapsulates the account balance and provides member functions for depositing and withdrawing money.

class BankAccount {

private:

    double balance;

public:

    BankAccount() {

        balance = 0.0;

    }

    

    void deposit(double amount) {

        balance += amount;

    }

    

    void withdraw(double amount) {

        if (balance >= amount) {

            balance -= amount;

        } else {

            cout << "Insufficient balance!" << endl;

        }

    }

    

    double getBalance() {

        return balance;

    }

};


int main() {

    BankAccount account;

    account.deposit(1000.0);

    account.withdraw(500.0);

    cout << "Balance: $" << account.getBalance() << endl;

    return 0;

}

Output:

Balance: $500

Conclusion

Encapsulation is a powerful concept in DSA that allows us to encapsulate data and methods within a class, providing data protection and code organization. By understanding and applying encapsulation, you can write efficient and secure code. Remember to practice encapsulation in various scenarios to strengthen your understanding of this fundamental concept in C++.

The document Encapsulation in C++ | DSA in C++ - Software Development is a part of the Software Development Course DSA in C++.
All you need of Software Development at this link: Software Development
153 videos|115 docs|24 tests

Top Courses for Software Development

153 videos|115 docs|24 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Semester Notes

,

MCQs

,

Previous Year Questions with Solutions

,

practice quizzes

,

Encapsulation in C++ | DSA in C++ - Software Development

,

study material

,

Objective type Questions

,

Encapsulation in C++ | DSA in C++ - Software Development

,

Free

,

shortcuts and tricks

,

Important questions

,

Sample Paper

,

video lectures

,

ppt

,

pdf

,

Extra Questions

,

Exam

,

Viva Questions

,

mock tests for examination

,

Encapsulation in C++ | DSA in C++ - Software Development

,

past year papers

,

Summary

;