Code For NonGeek
Would you like to react to this message? Create an account in a few clicks or log in to continue.

How do a virtual functions work in C++?

Go down

How do a virtual functions work in C++? Empty How do a virtual functions work in C++?

Post  skyboard Sun Sep 04, 2011 11:41 am

A virtual function depends on a "vtable" or "Virtual Table". If any function of a class in declared as virtual, a v-table is constructed which stores addresses of the virtual functions of this class.
The compiler also add a hidden vptr variable in all such classes which points to the vtable of that class. If a virtual functions is not overridden in the derived class, the vtable of the derived class stores the address of the function in his parent class. The v-table is used to resolve the address of the function, for whenever the virtual function is called. Thus dynamic binding in C++ is performed through the vtable mechanism.

C++ non-virtual function calls are resolved at compile time with static binding, while virtual function calls are resolved at run time with dynamic binding.

skyboard

Posts : 31
Join date : 2011-09-03

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum