Hello everyone,


In the case when function in derived class is virtual, but function in base class is not virtual, when we make base class pointer pointing to derived class' instance, the function in base will be invoked.

I am confused why not the function in Derived class is invoked (this is my question).

When making base pointer pointing to derived class' instance, the layout of derived class should begin with vtable of functions of derived class (virtual function of foo in Derived class in the sample), and the base pointer is pointing to the layout, so when invoking the derived class version function could be found in vtable and it should be invoked. How compiler process this situation internally?

Code:
#include <iostream>

using namespace std;

class Base {
public:
	void foo()
	{
		cout << "Base foo " << endl;
	}
};

class Derived: public Base {
public:
	virtual void foo()
	{
		cout << "Derived foo " << endl;
	}
};

int main()
{
	Derived d;
	Base* pb = dynamic_cast<Base*>(&d);
	pb->foo(); // output Base foo

	pb = static_cast<Base*>(&d);
	pb->foo(); // output Base foo

	pb = &d;
	pb->foo(); // output Base foo
	return 0;
}

thanks in advance,
George