Write a program in C++ to create abstract class Figure having pure virtual function
area(), and data members length, breadth. Derive classes Triangle and Rectangle from
Figure having member functions area(). Find area of triangle and rectangle using run
time polymorphism concept? [Note: sub classes does not contain any data members].
#include <iostream>
class Figure
{
protected:
double breadth;
double length;
public:
virtual double area() = 0;
};
class Rectangle : public Figure
{
public:
Rectangle(int a, int b)
{
this ->breadth = a;
this ->length = b;
}
virtual double area()
{
return this -> breadth * this -> length;
}
};
class Triangle : public Figure
{
public:
Triangle(int a, int b)
{
this ->breadth = a;
this ->length = b;
}
virtual double area()
{
return (this -> breadth * this -> length) / 2;
}
};
int main()
{
Figure* f = new Triangle(4, 5);
std::cout << "Area of this triangle is: " << f -> area() <<std::endl;
Figure* f1 = new Rectangle(3, 2);
std::cout << "Area of this rectangle is: " << f1 -> area() <<std::endl;
return 0;
}
Comments
Leave a comment