Tuesday, 29 November 2011

Basics of Virtual Functions


The address of all the functions are known at compile time with the exception of virtual functions. There address is not known at until run time, this is an example of late binding.
One of d factors deciding the size of an executable (.exe) depends on this binding if a lot of early binding is done d size tends to increase and with late binding the size tends to decrease.
In the world of VIRTUAL functions there are "VTABLES" and "VPTRS"
VTABLES: They are an array of function pointers which holds the addresses of all the virtual functions.
Only 1 VTABLE is generated for a single class
VPTRS: It is a pointer which points at a location inside the VTABLE.Each object will have a VPTR which points to the correct location in a VTABLE.

SO what happens when we call a virtual function

1.VPTR of that object is fetched
2.Offset in the VTABLE is calculated
3. At that offset is d function pointer which is pointing to the virtual function which is then fetched
4. finally the function call is made.

Though the actual memory footprint of a virtual function is very complex but dis is d crux of what happens behind and should give u a basic understanding.

NOTE: Compilers are smart enough to optimize VIRTUAL function calls.
For eg:
class A
virtual void func();
class B : public A
virtual void func();
int main()
A* obj = new B():
B* obj1 = new B():

obj.func(); \\Virtual function overhead, VTABLE lookup occurs here
obj1.func(); \\No overhead here simple member function call passing a "this" pointer.
return 0;

No comments:

Post a Comment