简体   繁体   中英

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

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 . 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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM