Programming

# Create a Class Shape with Functions to Find Area of the Shapes

Write a program to create a class – shape with functions to find area of the shapes and display the name of the shape and other essential components of the class. Create derived classes – circle, rectangle and trapezoid each having overridden function. Write a suitable program to illustrate the use of virtual function.

Algorithm:

• Start the program
• Enter the choice
• If choice = 1 then PUSH, else if choice = 2 then POP else if choice = 3 then TRAVERSE else if choice = 4 then EXIT
• Perform stack operation
• Exit the program

Source Code:

```#include<iostream.h>
#include<conio.h>
class shape
{
public:
float r,l1,b1,l2,b2,h2;
void inputc()
{
cout<<"\nEnter the radius of circle: ";
cin>>r;
}
void inputr()
{
cout<<"\n\nEnter the length and breadth of rectangle: ";
cin>>l1>>b1;
}
void inputt()
{
cout<<"\n\nEnter the length, breadth and height of trapezoid: ";
cin>>l2>>b2>>h2;
}
virtual void display()
{  cout<<"\nPlease enter the data: \n";   }
};
class circle: public shape
{
protected:
float ac;
public:
void input1()
{           inputc();           }
void display()
{
ac = 3.14159 * r * r;
cout<<"\nThe area is: "<<ac;
}
};

class rectangle: public shape
{
protected:
float ar;
public:
void input2()
{  inputr();   }
void display()
{
ar = l1 * b1;
cout<<"\nArea of rectangle is: "<<ar;
}
};
class trapezoid: public shape
{
protected:
float at;
public:
void input3()
{  inputt();        }
void display()
{
at = (h2/2) * (l2+b2);
cout<<"\nArea of trapezoid is: "<<at;
}
};
void main()
{
shape s; circle c; rectangle r; trapezoid t;
shape *shapeptr; shapeptr = &s;   shapeptr->display();
c.input1();           shapeptr = &c; shapeptr->display();
r.input2(); shapeptr = &r; shapeptr->display();
t.input3(); shapeptr = &t; shapeptr->display();
getch();
}```

#### Tuts

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.

## You may also like

Programming

Programming

#### Calculate the Factorial by Using Recursion

• January 26, 2016