Create a base class shape with two double type values and member functions to input the data and compute_area() for calculating area of figure. Derive two classes’ triangle and rectangle in cpp.

               HIERARCHICAL INHERITANCE


                         C++ Hierarchical Inheritance. When several classes are derived from the common base class it is called hierarchical inheritance. In C++ hierarchical inheritance, the feature of the base class is inherited onto more than one sub-class. For example, a car is a common class from which Audi, etc can be derived.




PROGRAM

Create a base class shape with two double type values and member functions to input the data and compute_area() for calculating the area of the figure. Derive two classes’ triangle and rectangle. Make compute_area() as a virtual function and redefine this function in the derived class to suit their requirements. Write a program that accepts dimensions of triangle/rectangle and displays calculated area. 

#include<iostream>
#include<conio.h>
using namespace std;
class shape
{
 public:
 double a,b;
virtual void accept()=0;
virtual void calarea()=0;
};

class triangle:public shape
{
  public:

  void accept()
  {
   cout<<"Enter base and height";
   cin>>a>>b;
  }
 void calarea()
  {  int area;
     area=0.5*a*b;
     cout<<area;

  }

  };
   class rectangle :public shape
{
  public:
  double area;
  void accept()
  {
   cout<<"Enter length and breadth";
   cin>>a>>b;
  }
  void calarea()
  {
   int area;
   area=a*b;
   cout<<area;

  }

};

 int main()
 {
  int n;
 // clrscr();
  shape *s;
triangle t;
rectangle r;
while(n!=3)
{
  cout<<"Enter 1 for area of triangle\n 2 for area of rectangle\n";
  cin>>n;
  switch(n)
  {
    case 1: s=&t;
     s->accept();
     s->calarea();
     break;

    case 2:s=&r;
    s->accept();
    s->calarea();
    break;
  }
}
  //getch();
  return 0;
 }

OUTPUT:

Enter 
1 for area of triangle
2 for area of rectangle
1
Enter base and height
23
43
494
Enter 
1 for area of triangle
2 for area of rectangle
2
Enter length and breadth
34
23
782


No comments:

Post a Comment

If you have any problems related to solutions or any concept please let me know.

Copyright (c) 2020 Custom Programs All Right Reserved

Pages