# Abstraction in C++

C++ProgrammingServer Side Programming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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:
public:
void setValues(int l, int b) {
length = l;
}
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
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:
public:
void setValues(int l, int b) {
length = l;
}
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();
Updated on 24-Jun-2020 11:25:15