Content deleted Content added
(27 intermediate revisions by 21 users not shown) | |||
Line 1:
{{Short description|Inheritable and overridable function or method for which dynamic dispatch is facilitated}}
{{more citations needed|date=March 2013}}
{{Polymorphism}}
In [[object-oriented programming]]
Most programming languages, such as [[JavaScript
== Purpose ==
{{
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 (computer programming)|pointer]] or [[Reference (computer science)|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 (linked) either
Virtual functions are resolved
Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code is compiled.{{Citation needed|date=October 2021}}
Line 21 ⟶ 22:
=== C++ ===
[[Image:ClassDiagram for VirtualFunction.png|400px|thumb|right|Class Diagram of Animal]]
For example, a base class <code>Animal</code> could have a virtual function <code>
<syntaxhighlight lang="cpp">
import std;
class Animal {
// Intentionally not virtual:
void
std::
}
virtual void
};
// The class "Animal" may possess a definition for Eat if desired.
class Llama : public Animal {
// The non virtual function Move is inherited but not overridden.
void
std::
}
};
</syntaxhighlight>
This allows a programmer to process a list of objects of class <code>Animal</code>, telling each in turn to eat (by calling <code>
=== C ===
In C, the mechanism behind virtual functions could be provided in the following manner:
<syntaxhighlight lang="c">
#include <stdio.h>
/* an object points to its class... */
typedef struct {
const
} Animal;
/* which contains the virtual function Animal.
typedef struct {
void (*
} AnimalVTable;
/*
it is not in the structure above.
void Move(struct Animal * self)▼
*/
void move(const Animal* self) {
printf("<Animal at %p> moved in some way\n", (void }
/*
Eat cannot know which function (if any) to call at compile time.
Animal.
*/ void
const AnimalVTable* vtable = self->vtable;
if (vtable->eat != NULL) {
} else {▼
▲ class->Eat(self); // execute Animal.Eat
▲ else
}
▲ fprintf(stderr, "Eat not implemented\n");
}
/*
*/
printf("<Llama at %p>
}
/* initialize class */
const
const
int main(void) {
/* init objects as instance of its class */
struct Animal animal = {
struct Animal llama = {
}
</syntaxhighlight>
Line 109 ⟶ 118:
Although pure virtual methods typically have no implementation in the class that declares them, pure virtual methods in some languages (e.g. C++ and Python) are permitted to contain an implementation in their declaring class, providing fallback or default behaviour that a derived class can delegate to, if appropriate.<ref>[https://en.cppreference.com/w/cpp/language/destructor#Pure_virtual_destructors Pure virtual destructors - cppreference.com]</ref><ref>[https://docs.python.org/3/library/abc.html "abc — Abstract Base Classes: @abc.abstractmethod"]</ref>
Pure virtual functions can also be used where the method declarations are being used to define an [[interface (Java)|interface]]
== Behavior during construction and destruction ==
Languages differ in their behavior while the [[Constructor (computer science)|constructor]] or [[Destructor (computer science)|destructor]] of an object is running. For this reason, calling virtual functions in constructors is generally discouraged.
In C++, the "base" function is called. Specifically, the most derived function that is not more derived than the current constructor or destructor's class is called.<ref name="cpp-std">{{cite web|url=http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf|title=N4659: Working Draft, Standard for Programming Language C++}}</ref>{{rp|§15.7.3}}<ref name=chen>{{cite web |title=What is __purecall? |last=Chen|first=Raymond|author-link=Raymond Chen|date=April 28, 2004 |url=https://devblogs.microsoft.com/oldnewthing/20040428-00/?p=39613}}</ref><ref>{{cite web |title=Never Call Virtual Functions during Construction or Destruction |last=Meyers|first=Scott|author-link=Scott Meyers|date=June 6, 2005 |url=http://www.artima.com/cppsource/nevercall.html}}</ref> If that function is a pure virtual function, then [[undefined behavior]] occurs.<ref
In Java and C#, the derived implementation is called, but some fields are not yet initialized by the derived constructor (although they are initialized to their default zero values).<ref>{{cite web |title=Joy of Programming: Calling Virtual Functions from Constructors |last=Ganesh|first=S.G.|date=August 1, 2011 |url=https://www.opensourceforu.com/2011/08/joy-of-programming-calling-virtual-functions-from-constructors/}}</ref> Some [[Design pattern (computer science)|design patterns]], such as the [[Abstract Factory Pattern]], actively promote this usage in languages supporting this 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 (computer programming)|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 in relation 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 behavior is a common source of programming errors if destructors are not virtual.
Line 125 ⟶ 134:
== See also ==
* [[Abstract method]]
* [[Inheritance (
* [[Superclass (computer science)
* [[Virtual inheritance]]
* [[Virtual class]]
* [[Interface (object oriented programming)]]
* [[Component Object Model|Component object model]] (Microsoft's COM)
* [[Virtual method table]]
|