Virtual function - wikipedia Virtual function This article may be too technical for most readers to understand. Please help improve it to make it understandable to non-experts, without removing the technical details. ( October 2017 ) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. ( March 2013 ) Polymorphism Ad hoc polymorphism Function overloading Operator overloading Parametric polymorphism Double dispatch Multiple dispatch Single and dynamic dispatch Subtyping Virtual function In object - oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the ( runtime ) polymorphism portion of object - oriented programming ( OOP ). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time. Contents 1 Purpose 2 Example 3 Abstract classes and pure virtual functions 4 Behaviour during construction and destruction 5 Virtual destructors 6 See also 7 References Purpose Further information : Dynamic dispatch The concept of the virtual function solves the following problem : In object - oriented programming, when a derived class inherits from a base class, an object of the derived class may be referred to via a pointer or reference of the base class type instead of the derived class type. If there are base class methods overridden by the derived class, the method actually called by such a reference or pointer can be bound either ' early ' ( by the compiler ), according to the declared type of the pointer or reference, or ' late ' ( i.e., by the runtime system of the language ), according to the actual type of the object referred to. Virtual functions are resolved ' late '. If the function in question is ' virtual ' in the base class, the most - derived class 's implementation of the function is called according to the actual type of the object referred to, regardless of the declared type of the pointer or reference. If it is not ' virtual ', the method is resolved ' early ' and the function called is selected according to the declared type of the pointer or reference. Virtual functions allow a program to call methods that do n't necessarily even exist at the moment the code is compiled. In C++, virtual methods are declared by prepending the virtual keyword to the function 's declaration in the base class. This modifier is inherited by all implementations of that method in derived classes, meaning that they can continue to over-ride each other and be late - bound. And even if methods owned by the base class call the virtual method, they will instead be calling the derived method. Overloading occurs when two or more methods in one class have the same method name but different parameters. Overriding means having two methods with the same method name and parameters. Overloading is also referred to as dynamic function mapping and overriding as function matching. Example Class Diagram of Animal For example, a base class Animal could have a virtual function eat. Subclass Llama would implement eat ( ) differently than subclass Wolf, but one can invoke eat ( ) on any class instance referred to as Animal, and get the eat ( ) behaviour of the specific subclass. class Animal ( public : void / * non-virtual * / move ( void ) ( std : : cout < < `` This animal moves in some way '' < < std : : endl ; ) virtual void eat ( void ) = 0 ; ) ; / / The class `` Animal '' may possess a definition for eat ( ) if desired. class Llama : public Animal ( public : / / The non virtual function move ( ) is inherited but not overridden void eat ( void ) override ( std : : cout < < `` Llamas eat grass ! '' < < std : : endl ; ) ) ; This allows a programmer to process a list of objects of class Animal, telling each in turn to eat ( by calling eat ( ) ), without needing to know what kind of animal may be in the list, how each animal eats, or what the complete set of possible animal types might be. Abstract classes and pure virtual functions A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed `` abstract '' and they can not be instantiated directly. A subclass of an abstract class can only be instantiated directly if all inherited pure virtual methods have been implemented by that class or a parent class. Pure virtual methods typically have a declaration ( signature ) and no definition ( implementation ). As an example, an abstract base class MathSymbol may provide a pure virtual function doOperation ( ), and derived classes Plus and Minus implement doOperation ( ) to provide concrete implementations. Implementing doOperation ( ) would not make sense in the MathSymbol class, as MathSymbol is an abstract concept whose behaviour is defined solely for each given kind ( subclass ) of MathSymbol. Similarly, a given subclass of MathSymbol would not be complete without an implementation of doOperation ( ). Although pure virtual methods typically have no implementation in the class that declares them, pure virtual methods in C++ are permitted to contain an implementation in their declaring class, providing fallback or default behaviour that a derived class can delegate to, if appropriate. Pure virtual functions can also be used where the method declarations are being used to define an interface - similar to what the interface keyword in Java explicitly specifies. In such a use, derived classes will supply all implementations. In such a design pattern, the abstract class which serves as an interface will contain only pure virtual functions, but no data members or ordinary methods. In C++, using such purely abstract classes as interfaces works because C++ supports multiple inheritance. However, because many OOP languages do not support multiple inheritance, they often provide a separate interface mechanism. An example is the Java programming language. Behaviour during construction and destruction Languages differ in their behaviour while the constructor or destructor of an object is running. For some languages, notably C++, the virtual dispatching mechanism has different semantics during construction and destruction of an object. While it is recommended that virtual function calls in constructors should be avoided for C++, in some other languages, for example C# and Java, the derived implementation can be called during construction and design patterns such as the Abstract Factory Pattern actively promote this usage in languages supporting the ability. Virtual destructors Object - oriented languages typically manage memory allocation and de-allocation automatically when objects are created and destroyed. However, some object - oriented languages allow a custom destructor method to be implemented, if desired. If the language in question uses automatic memory management, the custom destructor ( generally called a finalizer in this context ) that is called is certain to be the appropriate one for the object in question. For example, if an object of type Wolf that inherits Animal is created, and both have custom destructors, the one called will be the one declared in Wolf. In manual memory management contexts, the situation can be more complex, particularly as relates to static dispatch. If an object of type Wolf is created but pointed to by an Animal pointer, and it is this Animal pointer type that is deleted, the destructor called may actually be the one defined for Animal and not the one for Wolf, unless the destructor is virtual. This is particularly the case with C++, where the behaviour is a common source of programming errors. See also Inheritance Superclass Virtual inheritance Interface ( object oriented programming ) Component object model Virtual method table References Jump up ^ Meyers, Scott ( June 6, 2005 ). `` Never Call Virtual Functions during Construction or Destruction ''. Retrieved from `` https://en.wikipedia.org/w/index.php?title=Virtual_function&oldid=821335202 '' Categories : C++ Method ( computer programming ) Object - oriented programming Hidden categories : Wikipedia articles that are too technical from October 2017 All articles that are too technical Articles needing expert attention from October 2017 All articles needing expert attention Articles needing additional references from March 2013 All articles needing additional references Articles with example C++ code Talk Contents About Wikipedia Čeština Deutsch Español Français 한국어 Italiano Polski Português Română Русский Svenska Українська Tiếng Việt 中文 Edit links This page was last edited on 19 January 2018, at 20 : 46. Text is available under the Creative Commons Attribution - ShareAlike License ; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia ® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. About Wikipedia

Question: when do we need virtual functions in c++
Answer: when a derived class inherits from a base class, an object of the derived class may be referred to via a pointer or reference of the base class type instead of the derived class type