Search code examples
c++functionvirtual

Why is my virtual function not assigning values?


I am trying to use a virtual function to calculate area of rectangle and triangle like this:-

#include<iostream>
using namespace std;

class Shape{
   public:
   int width;
   int height;
   void get(){
       cin>>width;
       cin>>height;
   }

   virtual void area(){
       cout<<"Calculates area";
   }
};

class Triangle:public Shape{

  void area(){
      int a = height*width/2;
      cout<<a<<endl;
  }
};

class Rectangle:public Shape{

  void area(){
      int a = height*width;
      cout<<a<<endl;
  }
};





int main(){
    Shape shapeObj;
    shapeObj.get();

    Shape *ptr;
    Triangle trObj;
    Rectangle rectObj;

    ptr=&trObj;
    ptr->area();

    ptr=&rectObj;
    ptr->area();
}

But my program is returning 0 as the area of both shapes. I think the value of width and height is not assigned in the Triangle and Rectangle class.Can someone tell where am I going wrong?


Solution

  • The problem is that the width and height are assigned to the shapeObj variable

    Shape shapeObj;
    shapeObj.get();
    

    but you are using the trObj and rectObj variables to calculate the area.

    Triangle trObj;
    Rectangle rectObj;
    ptr=&trObj;
    ptr->area();
    ptr=&rectObj;
    ptr->area();
    

    Try this instead

    int main()
    {
        Triangle trObj;
        trObj.get();
        Shape* ptr=&trObj;
        ptr->area();
    
        Rectangle rectObj;
        rectObj.get();
        ptr=&rectObj;
        ptr->area();
    }
    

    Of course because you have two variables and are calling get twice then this code is going to ask for the width and height twice. If that is not what you want then think carefully about how you are doing the I/O in this program, and how it could be designed better (hint: do the I/O in main and use parameters and return values in your classes).