I have a base class pointer pointing to a derived class object. I am calling foo() function by using two different ways in the code below. Why does Derived::foo() get called in the first case? Shouldn’t (*obj).foo() call Base::foo() function as it has already been dereferenced?
class Base
{
public:
Base() {}
virtual void foo() { std::cout << "Base::foo() called" << std::endl; }
virtual ~Base() {};
};
class Derived: public Base
{
public:
Derived() : Base() {}
virtual void foo() { std::cout << "Derived::foo() called" << std::endl; }
virtual ~Derived() {};
};
int main() {
Base* obj = new Derived();
// SCENARIO 1
(*obj).foo();
// SCENARIO 2
Base obj1 = *obj;
obj1.foo();
return 0;
}
Note that
objis a misnomer here, since it doesn’t refer to an object, but to a pointer,(*ptr).foo()is just a roundabout way to doptr->foo().*ptrdoesn’t result in an object, but in a referenceBase&to the object. And a virtual function call through a reference is subject to dynamic dispatch, just as such a call through a pointer.What you do here is you create a totally new object through slicing: it just has the base class parts of
*ptr. What you want instead is this: