Â
In our daily life, we do use the internet through wifi or mobile data, we get almost everything on the internet with a click, it seems very easy using the internet. But, we don't know how the works in the backend or how we get all the things with a click. We don't know actually how much traveling the information does to reach us in milliseconds. This is a kind of abstraction in real life, that is providing essential information to the outside world and hiding their background details.
What is Data Abstraction in C++?
-> Data Abstraction means providing only important information to the user (outside world) and hiding the background details.
-> In C++, there are two types of Data Abstraction
1. Using Classes and Access Specifiers
- We implement a class in C++ with three access specifiers public, private, and protected. As we know, access specifiers are us to control the access given to the class members.
- Using the access specifiers we can implement the abstraction, in such a way that implementation details (private member variables) are hidden from the outside world while the interface(public member functions) can be provided to the outside world.
Example:
#include <iostream>
using namespace std;
class Name
{
private:
string name;
public:
void setname(string s)
{
name = s;
}
void printname()
{
cout << "My Name is " << name;
}
};
int main()
{
Name obj1;
obj1.setname("Rohan");
obj1.printname();
return 0;
}
Output:
2. Using Header Files.
- We all use header files in C++ i.e. predefined directives(functions).
- The most commonly used function which implements data abstraction is cin and cout in C++, we know its interface but don't know about the background details and inside functioning of these functions. Like these, many header files have functions that implement Data Abstraction in C++.Â
Some of them are listed below,
<math.h>
<string.h>
<stdlib.h>
<fstream.h>
<map.h>
<set.h>
<vector.h>
etc...
Example:
#include <iostream>
#include <string>
using namespace std;
class employee
{
int empId;
string name;
double salary, basic, allowances;
double calculateSalary(int empId)
{
salary = basic + allowances;
return salary;
}
public:
employee(int empId, string name, double basic, double allowances) : empId(empId), name(name), basic(basic), allowances(allowances)
{
calculateSalary(empId);
}
{
calculateSalary(empId);
}
void display()
{
cout << "EmpId : " << empId << "\nName : " << name << endl;
cout << "Employee Salary : " << salary;
}
};
int main()
{
employee emp(1, "Ben", 55000, 3245.43);
emp.display();
}
Output:
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP