Abstraction in C++

C++ProgrammingServer Side Programming

Abstraction involves providing only the pertinent information to the outside world and hiding the background details. It relies on the separation of interface and implementation for programming.

Classes provide abstraction in C++. They provide public methods for the outside world to manipulate data and keep the rest of the class structure to themselves. So the users can use the class as required without knowing how it has been implemented internally.

A program to implement abstraction in C++ using classes is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Abstraction {
   private:
   int length, breadth;
   public:
   void setValues(int l, int b) {
      length = l;
      breadth = b;
   }
   void calcArea() {
      cout<<"Length = " << length << endl;
      cout<<"Breadth = " << breadth << endl;
      cout<<"Area = " << length*breadth << endl;
   }
};
int main() {
   Abstraction obj;
   obj.setValues(5, 20);
   obj.calcArea();
   return 0;
}

Output

Length = 5
Breadth = 20
Area = 100

In the above program, the length and breadth in class Abstraction are private variables. There are public functions that initialize these variables and also calculate the area by multiplying length and breath. Hence, this class demonstrates abstraction. The code snippet for this is as follows.

class Abstraction {
   private:
   int length, breadth;
   public:
   void setValues(int l, int b) {
      length = l;
      breadth = b;
   }
   void calcArea() {
      cout<<"Length = " << length << endl;
      cout<<"Breadth = " << breadth << endl;
      cout<<"Area = " << length*breadth << endl;
   }
};

In the function main(), first an object of type Abstraction is defined. Then the function setValues() is called with the values 5 and 20. Finally, these values and the area are displayed using the function calcArea(). The code snippet for this is as follows.

Abstraction obj;
obj.setValues(5, 20);
obj.calcArea();
raja
Updated on 24-Jun-2020 11:25:15

Advertisements