heapuser
heapuser

Reputation: 331

Unable to access the base variables in the derrived class

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 ?

Upvotes: 0

Views: 338

Answers (2)

Kunal
Kunal

Reputation: 3535

your constructor of child class should be like following,

 Rectangle( int a=0, int b=0)
      :Shape(a, b) //call base class constructor
  {
      //Shape(a, b); // you are creating new object of shape here , not calling base constructor 
  }

Upvotes: 0

iammilind
iammilind

Reputation: 70000

The correct syntax is:

Rectangle( int a=0, int b=0) : Shape(a, b)
{                       //     ^^^^^^^^^^^^
}

You need to call Shape constructor as part of initializer list.
As in your example, if you write it as a statement,

{
  Shape(a,b);  // <--- no effect on Base part
}

then, a temporary Shape object is created and destroyed, so it has no effect.

Upvotes: 1

Related Questions