What is Virtual Function?




What is Virtual Function?

Virtual function is used via a pointer to class to determine which function definition will be used. To achieve runtime polymorphism we use the ptr to base class to refer to all derived object but the base pointer even when it is made to contain the address of derived classes it always executes the function in the base class.

To overcome this problem virtual function are used. When a function is made virtual C++ compiler determines which function to use at run time based on the type of object pointed by the base pointer rather than the type of the pointer.