simple real life example of code using abstraction in c++

1 answer

In this example, we will create a simple class called "Shape" that contains two pure virtual functions called "calculateArea()" and "calculatePerimeter()". We will then create two subclasses called "Rectangle" and "Circle" that inherit from the Shape class and implement the virtual functions.

```cpp
#include <iostream>

class Shape {
public:
virtual double calculateArea() = 0;
virtual double calculatePerimeter() = 0;
};

class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double calculateArea() {
return length * width;
}
double calculatePerimeter() {
return 2 * (length + width);
}
};

class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() {
return 3.14 * radius * radius;
}
double calculatePerimeter() {
return 2 * 3.14 * radius;
}
};

int main() {
Rectangle rect(5, 3);
Circle circle(2);

std::cout << "Rectangle area: " << rect.calculateArea() << std::endl;
std::cout << "Rectangle perimeter: " << rect.calculatePerimeter() << std::endl;

std::cout << "Circle area: " << circle.calculateArea() << std::endl;
std::cout << "Circle circumference: " << circle.calculatePerimeter() << std::endl;

return 0;
}
```

In this code, the Shape class serves as an abstraction for different shapes by declaring two pure virtual functions that represent common behavior for all shapes. The Rectangle and Circle classes then inherit from the Shape class and implement these functions by providing their specific formulas for calculating area and perimeter.

This example demonstrates how abstraction allows us to define a common interface for different classes while hiding the implementation details.
Similar Questions
    1. answers icon 1 answer
    1. answers icon 1 answer
  1. What is abstraction? Describe it in your OWN words.Give an example from your life where you use or have used abstraction.
    1. answers icon 1 answer
  2. which of the following is an adveantage of procedural abstractiona. program code is less complex b. all of these are advantages
    1. answers icon 1 answer
more similar questions