Answer to Question #274056 in C++ for Amit

Question #274056

 Write a program in C++ to create abstract class Figure having pure virtual function

area(), and data members length, breadth. Derive classes Triangle and Rectangle from

Figure having member functions area(). Find area of triangle and rectangle using run

time polymorphism concept? [Note: sub classes does not contain any data members].


1
Expert's answer
2021-12-09T17:38:15-0500
#include <iostream>

class Figure
{
protected:
    double breadth;
    double length;
public:
    virtual double area() = 0;
};

class Rectangle : public Figure
{
public:
    Rectangle(int a, int b)
    {
        this ->breadth = a;
        this ->length = b;
    }
    virtual double area()
    {
        return this -> breadth * this -> length;
    }
};

class Triangle : public Figure
{
    
public:
    Triangle(int a, int b)
    {
        this ->breadth = a;
        this ->length = b;
    }
    virtual double area()
    {
        return (this -> breadth * this -> length) / 2;
    }
};

int main()
{
    Figure* f = new Triangle(4, 5);
    std::cout << "Area of this triangle is: " << f -> area() <<std::endl;
    Figure* f1 = new Rectangle(3, 2);
    std::cout << "Area of this rectangle is: " << f1 -> area() <<std::endl;
 
    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