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 !

Recommended Answers

All 2 Replies

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.