How do a virtual functions work in C++?
Page 1 of 1
How do a virtual functions work in C++?
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.
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
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|