Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Don't get confused by that. "A pointer to derived class object is implicitly converted to a pointer to base class object" - This statement's significance is that suppose derived has some method derivedOnly(), which is not present in base. Now if you try bptr->derivedOnly(); then this will trow an error even when you are indeed referencing an object of derived.

So, bptr is indeed a pointer to base.

In this example:

base *bptr = new derived;
bptr->func();

the base class is just used someway as an interface to know which methods can be called, as it is pointing to a derived object instance. The vtable (http://en.wikipedia.org/wiki/Virtual_method_table) will make that the method from derived class is called.

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