I have a base class pointer pointing to derived class object. I am calling foo() function by using two different ways as mentioned below in Code. I want to know why in first case Derived:foo() is getting called.
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;
}