Virtual function: Difference between revisions

Content deleted Content added
 
(6 intermediate revisions by 3 users not shown)
Line 4:
In [[object-oriented programming]] such as is often used in [[C++]] and [[Object Pascal]], a '''virtual function''' or '''virtual method''' is an inheritable and [[Method overriding (programming)|overridable]] [[function (computer science)|function]] or [[method (computer science)|method]] that is [[dynamic dispatch|dispatched dynamically]]. Virtual functions are an important part of (runtime) [[Polymorphism (computer science)|polymorphism]] in [[object-oriented programming]] (OOP). They allow for the execution of target functions that were not precisely identified at compile time.
 
Most programming languages, such as [[JavaScript]], [[PHP]] and [[Python (programming language)|Python]], treat all methods as virtual by default<ref>{{Cite web|title=Polymorphism (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)|url=https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html|access-date=2020-07-11|website=docs.oracle.com}}</ref><ref>{{Cite web|title=9. Classes — Python 3.915.25 documentation|url=https://docs.python.org/3/tutorial/classes.html|access-date=20212025-0207-2305|website=docs.python.org}}</ref> and do not provide a modifier to change this behavior. However, some languages provide modifiers to prevent methods from being overridden by derived classes (such as the ''final'' and ''private'' keywords in [[Java (programming language)|Java]]<ref>{{Cite web|title=Writing Final Classes and Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)|url=https://docs.oracle.com/javase/tutorial/java/IandI/final.html|access-date=2020-07-11|website=docs.oracle.com}}</ref> and [[PHP]]<ref>{{Cite web|title=PHP: Final Keyword - Manual|url=https://www.php.net/manual/en/language.oop5.final.php|access-date=2020-07-11|website=www.php.net}}</ref>).
 
== Purpose ==
{{furtherFurther|Dynamic dispatch}}
The concept of the virtual function solves the following problem:
 
Line 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>Eateat</code>. Subclass <code>Llama</code> would implement <code>Eateat</code> differently than subclass <code>Wolf</code>, but one can invoke <code>Eateat</code> on any class instance referred to as Animal, and get the <code>Eateat</code> behavior of the specific subclass.
 
<syntaxhighlight lang="cpp">
import std;
 
class Animal {
public:
// Intentionally not virtual:
void Movemove() {
std::cout << println("This animal moves in some way" << std::endl);
}
 
virtual void Eateat() = 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 Eateat() override {
std::cout << println("Llamas eat grass!" << std::endl);
}
};
</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>Eateat</code>), 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.
 
=== C ===
 
In C, the mechanism behind virtual functions could be provided in the following manner:
Line 51 ⟶ 56:
 
/* an object points to its class... */
typedef struct {
struct Animal {
const struct AnimalVTable* *vtable;
} Animal;
 
/* which contains the virtual function Animal.Eateat */
typedef struct {
struct AnimalVTable {
void (*Eateat)(struct Animal* *self); // 'virtual' function
struct} AnimalVTable {;
};
 
/*
Since Animal.Movemove is not a virtual function
it is not in the structure above.
*/
void Movemove(const struct Animal* *self) {
printf("<Animal at %p> moved in some way\n", ( void* )(self));
}
 
/*
unlike Movemove, which executes Animal.Movemove directly,
Eat cannot know which function (if any) to call at compile time.
Animal.Eateat can only be resolved at run time when Eateat is called.
*/
void Eateat(struct Animal* *self) {
const struct AnimalVTable* *vtable = self->vtable;
if (vtable->Eateat != NULL) {
(*vtable->Eateat)(self); // execute Animal.Eateat
} else {
fprintf(stderr, "'Eateat' virtual method not implemented\n");
}
}
 
/*
implementation of Llama.Eateat this is the target function
to be called by 'void Eateat(struct Animal* *self).'
*/
static void _Llama_eat(struct Animal* *self) {
printf("<Llama at %p> Llamas eat grass!\n", ( void* )(self));
}
 
/* initialize class */
const struct AnimalVTable Animal = { NULL }; // base class does not implement Animal.Eat
const struct AnimalVTable Llama = { _Llama_eat }; // but the derived class does
 
int main(void) {
Line 98 ⟶ 103:
struct Animal animal = { &Animal };
struct Animal llama = { &Llama };
Movemove(&animal); // Animal.Movemove
Movemove(&llama); // Llama.Movemove
Eateat(&animal); // cannot resolve Animal.Eateat so print "Not Implemented" to stderr
Eateat(&llama); // resolves Llama.Eateat and executes
}
</syntaxhighlight>
Line 113 ⟶ 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]] - 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)|Java programming language]].
 
== Behavior during construction and destruction ==
Line 123 ⟶ 128:
 
== 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 134 ⟶ 139:
* [[Virtual class]]
* [[Interface (object oriented programming)]]
* [[Component Object Model|Component object model]] (Microsoft's COM)
* [[Virtual method table]]