0

Hi there,

I am implementing the concept of polymorphism and write following program of shapes.

#include <iostream>

using namespace std;

class Shape
{
    protected:

        double width, height;

    public:

        void set(double w, double h)
        {
            width = w;
            height = h;
        }

        virtual double get()
        {
            return 0;
        }
};

class Square: public Shape
{
    public:

        double get()
        {
            return (width*width);
        }
};

class Rectangle: public Shape
{
    public:

        double get()
        {
            return (width*height);
        }
};

class Triangle: public Shape
{
    public:

        double get()
        {
            return 1/2*(width * height);
        }
};

int main()
{

    Shape s;
    Square sq;
    Rectangle rec;
    Triangle tri;

    Shape *p1 = &sq;
    Shape *p2 = &rec;
    Shape *p3 = &tri;

    p1->set(2, 2);
    p2->set(2, 4);
    p3->set(4, 8);      //problem is here

    cout<<"Area of square : " <<p1->get() <<endl;
    cout<<"Area of rectangle : " <<p2->get() <<endl;
    cout<<"Area of triangle : " <<p3->get() <<endl;       //output is 0.

    return 0;
}

But getter function of triangle is not giving the expcected output, it gives output 0. Please tell me where is the problem. Thanks !

2
Contributors
2
Replies
18
Views
4 Years
Discussion Span
Last Post by new_developer
1

Line 51: 1/2 is integer division. So the outcome multipied with whatever will be zero! Use 0.5 or 1.0/2 instead.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.