The following compiled code is showing the resulting area of zero. Some how the width and height variables are still remaining as zero even though we set it using the base constructor.
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
cout << shape->area() << endl;
// store the address of Triangle
shape = &tri;
// call triangle area.
cout << shape->area() << endl;
return 0;
}
Output:
Rectangle class area :
0
Rectangle class area :
0
Trying to find out why the area is zero and how to make the pgm to print the actual area ?
The correct syntax is:
You need to call
Shapeconstructor as part of initializer list.As in your example, if you write it as a statement,
then, a temporary
Shapeobject is created and destroyed, so it has no effect.