In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of OOP.
The purpose of having a virtual function is as follows:
In OOP when a derived class inherits a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class methods overridden by the derived class, the method call behaviour is ambiguous.
The distinction between virtual and non-virtual resolves this ambiguity. If the function in question is designated "virtual" in the base class then the derived class's function would be called (if it exists). If it is not virtual, the base class's function would be called.
Virtual functions overcome the problems with the type-field solution by allowing the programmer to declare functions in a base class that can be redefined in each derived class.
Programming language supports for virtual function:
C++: virtual methods are declared by using the virtual keyword followed by the function name and the parenthesis ().
Java: In Java, all non-static methods are by default "virtual functions
." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.
To override a method, use an annotation '
' (could be omitted) followed by function definition.
Python: In Python all class functions (methods) are virtual. And no special keywords needed to make overriding or virtualization happen. It just works automatically!