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;
}
There are 3 distinct objects in
main. Apolygoncalledp, arectanglecalledr, and atriangle t. You callsetValueonly on thepolygonobject.The other objects have their members uninitialized. You should initialize the members and then I suppose you want to call
setValuefor the other instances as well: