Answer to Question #213579 in C++ for shalini

Question #213579

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.


1
Expert's answer
2021-07-05T01:07:18-0400
#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;   
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS