I am trying to get a grasp about Virtual functions and inheritance in C++. In the example code below, I have two classes AreaCube (base class) and SideAreaRatio (derived class). I am trying to call the virtual function "area" in base class from another function "ratio" which is inside the derived class. And I am trying to achieve this, using an instance of the base class. But for some reason which I am not familiar of, I am seeing weird answer being generated. Please enlighten me here of what is going on!
#include<iostream> using namespace std; class AreaCube { public: int side; AreaCube() {}; AreaCube(int s) { side = s; } virtual ~AreaCube() {}; virtual int area() { cout<< "calling.. " << endl; int area = side*side*side; return area; } }; class SideAreaRatio:public AreaCube { public: SideAreaRatio(int s) { side = s; }; ~SideAreaRatio() {}; float ratio() { AreaCube a; int area = a.area(); cout<< area << endl; return (side/area); } }; int main() { AreaCube* ac = new AreaCube(2); cout<< ac->area() << endl; SideAreaRatio* sar = new SideAreaRatio(4); cout<< sar->ratio() << endl; } Expected Output:
calling.. 8 calling.. 8 0.3333 Generated Output:
calling.. 8 calling.. -1265467392 0