C++ – Purpose of Virtual Member Functions

c++overridingredefinitionvirtual-functions

What is the difference member between function overriding and virtual functions in C++?

Virtual member functions can be overridden in derived classes.
Redefining a function in a derived class is called function overriding.

Why do we actually have virtual functions?

Best Answer

Virtual function / method is simply a function whose behavior can be overriden within a subclass (or in C++ terms a derived class) by redefining how the function works (using the same signature).

Think of a base class mammal with a speak function. The function is void and simply couts how a mammal speaks. When you inherit from this class you can override the speak method so that dogs go "Arf Arf!" and cats go "Meow Meow".

Your question seems to ask what are the differences, well there are none because with virtual functions one can override the behavior of these functions. You may be after the difference between overriding functions and overloading them.

Overloading functions means to create a function with the same name but different arguments i.e. different number- and type-of argument(s). Here is an explanation on overloading in C++ from IBM's site:

Overloading (C++ only) If you specify more than one definition for a function name or an operator in the same scope, you have overloaded that function name or operator. Overloaded functions and operators are described in Overloading functions (C++ only) and Overloading operators (C++ only), respectively.

An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different types.

If you call an overloaded function name or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution, as described in Overload resolution (C++ only).

As for the full rational reason for situations where virtual functions are required, this blog post gives a good one: http://nrecursions.blogspot.in/2015/06/so-why-do-we-need-virtual-functions.html

Related Question