Write a c++ program to calculate the area and perimeter of rectangle using concept of inheritance
Certainly! Below is an example of a C++ program that demonstrates the concept of inheritance to calculate the area and perimeter of a rectangle. In this program, we will create a base class `Shape` that handles basic shape-related functionalities, and a derived class `Rectangle` that implements specific functionalities for a rectangle.
```cpp
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
// Function to calculate area (to be overridden)
virtual double area() = 0;
// Function to calculate perimeter (to be overridden)
virtual double perimeter() = 0;
};
// Derived class
class Rectangle : public Shape {
private:
double length;
double width;
public:
// Constructor to initialize the rectangle dimensions
Rectangle(double l, double w) : length(l), width(w) {}
// Override area calculation
double area() override {
return length * width;
}
// Override perimeter calculation
double perimeter() override {
return 2 * (length + width);
}
};
int main() {
double length, width;
// Get user input
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << "Enter the width of the rectangle: ";
cin >> width;
// Create a Rectangle object
Rectangle rectangle(length, width);
// Calculate and display the area and perimeter
cout << "Area of the rectangle: " << rectangle.area() << endl;
cout << "Perimeter of the rectangle: " << rectangle.perimeter() << endl;
return 0;
}
```
### Explanation:
1. **Base Class (`Shape`)**: This class contains two pure virtual functions `area()` and `perimeter()`. This makes it an abstract class, meaning you cannot instantiate it directly.
2. **Derived Class (`Rectangle`)**: The `Rectangle` class inherits from `Shape` and must implement the `area()` and `perimeter()` methods. It also has private attributes `length` and `width` to hold the dimensions of the rectangle.
3. **Constructor**: The constructor of the `Rectangle` class initializes the rectangle's length and width.
4. **Main Function**: The `main()` function requests user input to get the rectangle's dimensions, creates a `Rectangle` object, and then calls the `area()` and `perimeter()` methods to display the results.
### How to Compile and Run:
To compile and run the program, please follow these steps:
1. Save the code in a file named `RectangleAreaPerimeter.cpp`.
2. Open your terminal or command prompt and navigate to the directory where the file is saved.
3. Compile the program using:
```bash
g++ RectangleAreaPerimeter.cpp -o RectangleAreaPerimeter
```
4. Run the generated executable:
```bash
./RectangleAreaPerimeter
```
Now, the program will prompt you to enter the dimensions of the rectangle and will subsequently display the area and perimeter.