What do you mean by virtual function? How does a virtual function help to achieve run time plymorphism?

Subject Object Oriented Programming
NU Year Set: 5.(a) Marks: 5 Year: 2009

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

Virtual member function has what we call late binding. In compiled languages (like C++), function calls are resolved statically (on compile time). That means that the compiler/linker resolves the exact function (finds its entrypoint address) and that function is the only one that can be called at the point of the code. Virtual functions, on the other hand, are resolved dynamically; the compiler generates code that uses the so-called virtual functions table at run time and calls a particular implementation of the member function based on the actual type of the object. That comes with a bit of an overhead, of course.

Login to post your comment.