Can't a base class pointer which is pointing to derived class access the public data members of base class?

334 Views Asked by At

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;
}
1

There are 1 best solutions below

0
463035818_is_not_an_ai On

There are 3 distinct objects in main. A polygon called p, a rectangle called r, and a triangle t. You call setValue only on the polygon object.

The other objects have their members uninitialized. You should initialize the members and then I suppose you want to call setValue for the other instances as well:

class polygon{  
    public:
        int height = 0; // initializer for members
        int width = 0;
// ....

// in main
// ok
polygon* base;
base = &p;
base->setValue();

base=&r;
base->setValue(); // <-- this was missing
std::cout<<"\nArea of rectangle is "<<base->calculateArea();

base=&t;
base->setValue(); // <-- this was missing
std::cout<<"\nArea of triangle "<<base->calculateArea();