Question

In C++, i am not able to understand, when a base class pointer stores the address of derived class object it is not able to call the derived class member function?

#include <iostream>
using namespace std;

class Base
{
public:
    virtual void show()
    {
        cout<<" In Base ";
    }
};

class Derived: public Base
{
public:
    int x;
    void show()
    {
        cout<<"In Derived ";
    }
    Derived()
    {
        x = 10;
    }
};

int main(void)
{
    Base *bp, b;
    Derived d;
    bp = &d;
    bp->show();
    cout << bp->x;  
    return 0;
}

According to me: derived d => allocates the memory to this object(therefore to x also ) say at address 200, bp = &d; => it allocated the address 200 to bp. Now it should be able to call bp->x? But it gives a error.

Was it helpful?

Solution 3

In C++, i am not able to understand, when a base class pointer stores the address of derived class object it is not able to call the derived class member variable?

Well yes you can, you just need to cast the pointer to the class where the member variable is present

cout << dynamic_cast<Derived*>(bp)->x;

OTHER TIPS

bp->x gives an error because bp is a pointer to an object of type Base, and Base doesn't have a variable called x, only Derived does.

If x was moved up into Base it would be accessible from both Base and Derived if it's public or protected.

Binding of names happens in run time. so at compilation bp is of type base. so compiler doesn't know anything about derived type assignment. so its saying there is no variable called x in base.

That's where concept of virtual functions come into picture. but hey are only for functions not variables.

Why is bp->x is a error?

Because at compile time, the compiler can't tell what it points to. What if it was actually, a pointer to the base class? Then, x would be completely absent from the underlying object...

To answer the title question: when you have a pointer to base class that actually points to a derived class instance, then a call to a public functions declared virtual in the based class and reimplemented in the derived class will end up being a call to the derived class' implementation of that function (there are subtelties involved, with private/public access and name hiding that may interfere, but this is roughly how it works).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top