Create a base class called Shape which has two double type values. Use member function getdata() to get the values. Use a virtual function display_area() to display the area. Derive two specific classes called Triangle and Rectangle from the base class Shape. Redefine display_area() in the derived classes. Write a program that, based on the user's choice, creates a rectangle or triangle object during runtime, points that object with a Shape class pointer, and calls the display_ area() method with that pointer.
#include <iostream>
using namespace std;
class Shape {
public: double a, b;
void get_data ()
{
cin>>a>>b;
}
virtual void display_area () = 0;
};
class Triangle:public Shape
{
public: void display_area ()
{
cout<<"Area of triangle "<<0.5*a*b<<endl;
}
};
class Rectangle:public Shape
{
public: void display_area ()
{
cout<<"Area of rectangle "<<a*b<<endl;
}
};
int main()
{
Triangle t;
Shape *st = &t;
cout<<"Enter base and altitude: ";
st->get_data();
st->display_area();
Rectangle r;
Shape *sr = &r;
cout<<"Enter length and breadth: ";
sr->get_data();
sr->display_area();
return 0;
}
Comments
Leave a comment