In dynamic binding
, the function call is bound to the function implementation based on the type of object to which the pointer is pointing to.
Suppose we have the following code :
base *bptr = new derived;
bptr->func();
Let the function func
be declared virtual in the base class. Then the derived class's version of virtual function func
will be invoked at run-time due to dynamic binding.
I understand the above concept.
But i got confused by the following concept which i studied after studying the above concept.
In the above code snippet, a pointer to derived class object is implicitly converted to a pointer to base class object. Then bptr
will be actually pointing to the base class sub-object of derived class object and not pointing to the derived class object.
Since the base class pointer bptr
is pointing to base class sub-object, during run-time shouldn't the base class's version of virtual function func
be invoked?
It seems that you are missing what dynamic binding actually means. It means exactly that even if the pointer (statically) refers to the base sub object the call will be dispatched to the (dynamic) type of the complete object.
The common implementation is by means of a virtual function table. The base sub object will store as a hidden member a pointer to the virtual function table of the actual complete type to which it belongs. All calls to virtual functions (for which dynamic dispatch is not disabled) are routed through that extra level of indirection ensuring that the final overrides will be called.
As to the specifics of how that table and the hidden pointer are managed, the compiler builds e tables for each type with virtual functions, and injects code to the different constructors to update the pointers accordingly. So while building the base subobject the pointer refers to the base vtable, but before entering the derived constructor the injected code will update the pointer (in base) to refer to the derived vtable.