BCA
Object Oriented Programming using C++ Practical
Madras University
Program 9
Create a class to represent a 2-d shape and derive classes to represent a triangle,
rectangle and circle. Write a program using run-time polymorphism to compute the area of
the figures.
SOURCE CODE:
#include <iostream>
#include <cmath> // for M_PI
using namespace std;
// Base class for 2D shapes
class Shape {
public:
virtual double area() const = 0; // Pure virtual function to compute area
virtual ~Shape() = default; // Virtual destructor
};
// Derived class for Triangle
class Triangle : public Shape {
private:
double base;
double height;
public:
Triangle(double b, double h) : base(b), height(h) {}
double area() const override {
cout<<"Triangle Shape"<<endl;
return 0.5 * base * height;
}
};
// Derived class for Rectangle
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
cout<<"Rectangle Shape"<<endl;
return width * height;
}
};
// Derived class for Circle
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
cout<<"Circle Shape"<<endl;
return M_PI * radius * radius;
}
};
int main() {
// Creating objects for each shape
Shape* shapes[] = {
new Triangle(3.0, 4.0),
new Rectangle(5.0, 6.0),
new Circle(7.0)
};
// Computing and displaying the area of each shape
for (Shape* shape : shapes) {
cout << "Area: " << shape->area() << endl;
}
// Cleaning up dynamically allocated memory
for (Shape* shape : shapes) {
delete shape;
}
return 0;
}
OUTPUT:
Triangle Shape
Area: 6
Rectangle Shape
Area: 30
Circle Shape
Area: 153.938
Explanation:
Base Class
Shape
:Shape
is an abstract base class with a pure virtual functionarea()
.- The destructor is virtual to ensure proper cleanup of derived class objects.
Derived Classes:
Triangle
,Rectangle
, andCircle
classes inherit fromShape
.- Each class implements the
area()
function to calculate the area specific to the shape.
Main Function:
- An array of pointers to
Shape
objects is created, each pointing to a different shape. - The
area()
function is called on each shape object, demonstrating runtime polymorphism. - Memory allocated with
new
is released withdelete
.
- An array of pointers to
No comments:
Post a Comment