I have created a base class Polygon and declared two data members - height and width as public. Also a virtual function - calculateArea(). Then the two derived classes rectangle and triangle have a function calculateArea(). I want to override the base class function and each of the derived class use its own calculateArea(). The output is not coming as expected and it is 0 or some random value. You can see the code below and tell me where I am going wrong.
#include<bits/stdc++.h>
using namespace std;
class polygon{
public:
int height;
int width;
void setValue()
{
cout<<"\nEnter height and width ";
cin>>height>>width;
}
virtual int calculateArea(){
}
};
//Inheritance
class rectangle:public polygon
{
private:
string name;
public:
int calculateArea()
{
return height*width;
}
};
class triangle:public polygon
{
public:
int calculateArea()
{
return (height*width)/2;
}
};
int main()
{
polygon p;
rectangle r;
triangle t;
polygon* base;
base = &p;
base->setValue();
base=&r;
cout<<"\nArea of rectangle is "<<base->calculateArea();
base=&t;
cout<<"\nArea of triangle "<<base->calculateArea();
return 0;
}
base->setValue(),basepoints atpso the call ofbase->setValue()reads values ofp.heightandp.width. Then you assignbaseso it points at ar, who'sheightandwidthmembers are unintialised.publicaccess does not mean thatpandrsomehow share the same data - they are distinct objects.