Data Abstraction in C++ : Types & Use-Cases [With Examples]

Updated on August 7, 2024

Article Outline

Are you tired of dealing with complex code? Do you wish there was a way to simplify it? That’s where data abstraction in C++ comes in.

 

It’s a very useful concept in object-oriented programming (OOP) that allows us to present only the important information and hide irrelevant information. It allows one to concentrate more on what an object does rather than how it does it. This separation makes our programs easier to design and maintain.

 

Data abstraction facilitates the clean division of an object’s implementation from its interface. This streamlines our code, making it simpler to handle and comprehend. Data abstraction allows us to write reusable, adaptable programs.

 

We can think of it like using a TV remote. We only need to know which buttons to press, not how the TV works internally.

How Abstraction Enhances Code Reusability and Security

Worried about repeating code and potential security issues? Data abstraction in C++ can help.

 

It makes our code reusable and secure.

 

Enhancing Code Reusability

 

  • Write Once, Use Everywhere: With abstraction, we write code once and reuse it across different parts of our program.
  • Function Libraries: Create libraries of functions and classes to use them in various projects.
  • Example: A class for user authentication can be used in multiple applications.

Improving Security

 

  • Hide Sensitive Data: Abstraction hides sensitive data and implementation details.
  • Access Control: Use access specifiers to control who can see and modify your data.
  • Example: A banking system where the account balance is private, and only specific methods can change it.

 

Also read: Learn C++ Programming

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Types of Abstraction in C++

1. Control Abstraction: Simplifying Program Control Flow

 

We may better regulate the complexity of the control flow in our program by using control abstraction. To write compact and understandable code, we make use of functions, loops, and conditionals.

 

It simply displays important information about the implementation and excludes irrelevant details.

 

For instance, instead of writing the same code again and again, one can develop a function and call it every time.

 

2. Data Abstraction: Encapsulating Data with Classes

 

The goal of data abstraction is to mask all aspects of data manipulation and storage. Classes are used to organise related functions and data.

 

This helps us create a clear interface for interacting with our data while keeping the implementation details hidden.

Benefits of Using Data Abstraction in C++

Why should we bother with data abstraction?

Enhancing Code Reusability and Reducing Redundancy

  • We write code once and reuse it everywhere.
  • This saves time and effort.

Improving Code Readability and Maintainability

  • Our code becomes cleaner and easier to read.
  • We can maintain and update it without hassle.

Protecting Class Internals from User Errors

  • Users can’t mess with the internals.
  • This keeps our code safe and sound.

Implementing Data Abstraction in C++

Using Classes and Objects to Achieve Data Abstraction

Classes are the backbone of data abstraction in C++. They allow us to create objects that represent real-world entities.

 

Here’s a simple example of a class that represents a bank account:

#include <iostream> using namespace std;  class BankAccount { private: int balance;  public: BankAccount(int initial_balance) { balance = initial_balance; }  void deposit(int amount) { balance += amount; }  void withdraw(int amount) { if (amount <= balance) { balance -= amount; } else { cout << "Insufficient funds" << endl; } }  int getBalance() { return balance; } };  int main() { BankAccount account(1000); int depositAmount, withdrawAmount;  cout << "Enter amount to deposit: "; cin >> depositAmount; account.deposit(depositAmount);  cout << "Enter amount to withdraw: "; cin >> withdrawAmount; account.withdraw(withdrawAmount);  cout << "Current balance: " << account.getBalance() << endl;  return 0; }

Output:

Enter amount to deposit: 400 Enter amount to withdraw: 150 Current balance: 1250

The Role of Header Files in Data Abstraction

Another method for achieving data abstraction is using header files. They enable us to divide our code into distinct files, which improves organisation and manageability.

 

We might, for instance, put the BankAccount class definition in a header file and use it in our main application.

Using Access Specifiers for Data Abstraction in C++

We may manage who has access to the members of our classes by using the public, private, and protected access specifiers.

 

  • Public members are accessible from anywhere in the program.
  • Private members are only accessible within the class itself.
  • Protected members are accessible within the class and its derived classes.

Here’s how we can use these access specifiers:

#include <iostream> using namespace std;  class Vehicle { private: int speed;  protected: void setSpeed(int s) { speed = s; }  public: void showSpeed() { cout << "Speed: " << speed << " km/h" << endl; } };  class Car : public Vehicle { public: void accelerate() { setSpeed(120); } };  int main() { Car myCar; myCar.accelerate(); myCar.showSpeed();  return 0; }

Output:

Speed: 120 km/h

This code shows how we can use access specifiers to control how members of a class are accessed and modified.

Using Access Specifiers for Data Abstraction in C++

Why worry about someone messing with your code’s internals? With C++ access specifiers, we control who sees what.

 

It can be used to enforce restrictions and limitations on class members to help us protect sensitive data and control access.

 

We have three types: public, private, and protected.

Public Specifiers

Public members are open to all. Anyone can access them from anywhere in the program.

 

For example:

#include <iostream> using namespace std;  class Person { public: string name; void setName(string newName) { name = newName; } };  int main() { Person person; person.setName("Murali"); cout << "Name: " << person.name << endl; return 0; }

Private Specifiers

Private members stay hidden. Only the class itself can access these.

Here’s a quick example:

#include <iostream> using namespace std;  class Person { private: string name; public: void setName(string newName) { name = newName; } string getName() { return name; } };  int main() { Person person; person.setName("Neha"); cout << "Name: " << person.getName() << endl; return 0; }

Protected Specifiers

Protected members are like private members. They are only accessible within the class and its derived classes.

 

Take a look:

#include <iostream> using namespace std;  class Person { protected: string name; public: void setName(string newName) { name = newName; } };  class Employee : public Person { public: void display() { cout << "Employee Name: " << name << endl; } };  int main() { Employee emp; emp.setName("Suman"); emp.display(); return 0; }

Control Abstraction in C++: Key Concepts and Examples

How do we make our code cleaner and easier to manage? Control abstraction is the answer.

 

It helps us by abstracting away complex control flows.

Higher-Order Functions

Higher-order functions take other functions as arguments or return them as results. They simplify complex operations.

 

For instance, sorting with a custom comparator:

#include <iostream> #include <vector> #include <algorithm>  using namespace std;  bool compare(int a, int b) { return a > b; }  int main() { vector<int> numbers = {1, 4, 2, 8, 5}; sort(numbers.begin(), numbers.end(), compare);  for(int num : numbers) { cout << num << " "; }  return 0; }

The DRY Principle

The DRY (Don’t Repeat Yourself) principle encourages us to reuse code instead of duplicating it.

 

For example, creating a reusable function:

#include <iostream> using namespace std;  void printMessage(string message) { cout << message << endl; }  int main() { printMessage("Hello, World!"); printMessage("Welcome to C++ programming."); return 0; }

Practical Examples of Data Abstraction in C++

Example 1: Implementing a Calculator Class

Here’s a simple calculator that adds and subtracts numbers:

#include using namespace std; class Calculator { private: int result; public: Calculator() { result = 0; } void add(int value) { result += value; } void subtract(int value) { result -= value; } int getResult() { return result; } }; int main() { Calculator calc; int num1, num2; cout << "Enter first number: "; cin >> num1; cout << "Enter second number: "; cin >> num2; calc.add(num1); calc.subtract(num2); cout << "Result: " << calc.getResult() << endl; return 0; }

Output:

Enter first number: 7 Enter second number: 10 Result: -3

Example 2: Implementing a Simple Banking System

A simple banking system with deposit and withdrawal functions:

#include <iostream> using namespace std;  class BankAccount { private: int balance; public: BankAccount(int initial_balance) { balance = initial_balance; } void deposit(int amount) { balance += amount; } void withdraw(int amount) { if (amount <= balance) { balance -= amount; } else { cout << "Insufficient funds" << endl; } } int getBalance() { return balance; } };  int main() { BankAccount account(1000); int depositAmount, withdrawAmount;  cout << "Enter amount to deposit: "; cin >> depositAmount; account.deposit(depositAmount);  cout << "Enter amount to withdraw: "; cin >> withdrawAmount; account.withdraw(withdrawAmount);  cout << "Current balance: " << account.getBalance() << endl;  return 0; }

Output:

Enter amount to deposit: 200 Enter amount to withdraw: 700 Current balance: 500

Example 3: Abstracting Details in a Smart Home System

Managing smart devices with a simple class:

#include <iostream> using namespace std;  class SmartHome { private: bool lightsOn; bool thermostatOn;  public: SmartHome() { lightsOn = false; thermostatOn = false; }  void toggleLights() { lightsOn = !lightsOn; }  void toggleThermostat() { thermostatOn = !thermostatOn; }  void showStatus() { cout << "Lights: " << (lightsOn ? "On" : "Off") << endl; cout << "Thermostat: " << (thermostatOn ? "On" : "Off") << endl; } };  int main() { SmartHome home;  home.toggleLights(); home.toggleThermostat(); home.showStatus();  return 0; }

Output:

Lights: On Thermostat: On

Example 4: Creating a Library Management System

A class to manage library books:

#include <iostream> #include <vector> using namespace std;  class Book { private: string title; string author; int year;  public: Book(string t, string a, int y) : title(t), author(a), year(y) {}  void display() { cout << "Title: " << title << ", Author: " << author << ", Year: " << year << endl; } };  class Library { private: vector<Book> books;  public: void addBook(Book b) { books.push_back(b); }  void showBooks() { for (Book b : books) { b.display(); } } };  int main() { Library lib; lib.addBook(Book("India that is Bharat", "J Sai Deepak", 2011)); lib.addBook(Book("Savarkar: Echoes from a Forgotten Past", "Vikram Sampath", 2019));  lib.showBooks();  return 0; }

Output:

Title: India that is Bharat, Author: J Sai Deepak, Year: 2011 Title: Savarkar: Echoes from a Forgotten Past, Author: Vikram Sampath, Year: 2019

Conclusion

Data abstraction in C++ is an important concept that helps us write better code. It hides unnecessary details and exposes only essential features, enhancing code reusability and security. To control who can interact with the data to prevent any misuse, we use access specifiers.

 

Data abstraction has many real-life applications, and we delved into some of them in this web blog.

 

We also delved into practical examples, demonstrating how data abstraction simplifies complex systems, from banking systems to smart home devices.

 

Through data abstraction, it is possible to enhance the code design and maintain the codes easily.

 

In other words, data abstraction in C++ is a vital concept that enhances efficiency and has desirable characteristics.

FAQs
Classes and objects group data and functions, hiding internal details. They provide a clear interface for interaction.
Control abstraction simplifies control flows with functions and loops. Data abstraction hides data details using classes and objects.
Yes, examples include:
  • Banking systems hiding account details.
  • Smart home systems abstracting device controls.
Access specifiers control who can see and modify class members. They help hide sensitive data and protect internal implementation.

Updated on August 7, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved