
2.create class. Shape accepts two values (Data Type: Double). Create two derived classes Triangle and Rectangle ; calculate area of Triangle and rectangle using data members from base class. Use one virtual function to display data.

The given code defines a base class "Shape" to represent two different derived classes Triangle and Rectangle. Each of these two classes has a member function displayArea()to display the area of relevant shape on the screen and a member function getdata() to initialize base class data members. In case of Triangle class, these two values of base class will treated as base and height whereas in Rectangle these two values of base class will treated as length and breadth of rectangle.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Shape
{
protected :
double x0, y0;
public :
void getdata(double x, double y)
{
x0 = x;
y0 = y;
}
virtual void displayArea() = 0;
};
class Triangle : public Shape
{
public :
void getdata(double x, double y)
{
Shape :: getdata(x,y);
}
void displayArea()
{
double area = (x0 * y0)/2.0;
cout << "\n Area of triangle = " << area;
}
};
class Rectangle : public Shape
{
public :
void getdata(double x, double y)
{
Shape :: getdata(x,y);
}
void displayArea()
{
double area = (x0 * y0);
cout << "\n Area of rectangle = " << area;
}
};
void main()
{
Triangle *tptr;
Rectangle *rptr;
Shape *sptr[2];
int i;
tptr = new Triangle;
rptr = new Rectangle;
tptr->getdata(20.0,30.0);
rptr->getdata(20.0,20.0);
sptr[0] = tptr;
sptr[1] = rptr;
for(i=0; i<2; i++)
sptr[i]->displayArea();
getch();
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.