Information about Virtual Functions
In object-oriented programming (OOP), a virtual function or virtual method is a function whose behavior, by virtue of being declared "virtual," is determined by the definition of a function with the same signature furthest in the inheritance lineage of the instantiated object on which it is called. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP).
In OOP when a derived class inherits from 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 functions overridden by the derived class, a problem then arises when a derived object has been cast as the base class type. When a derived object is referred to as being of the base's type, the desired function call behavior is ambiguous.
The distinction between virtual and not virtual is provided to solve this issue. If the function in question is designated "virtual" 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.
This allows a programmer to process a list of objects of class
The following is an example in C++:
class Animal { public: virtual void eat() { cout << "I eat like a generic Animal.\n"; } };
class Wolf : public Animal { public: void eat() { cout << "I eat like a wolf!\n"; } };
class Fish : public Animal { public: void eat() { cout << "I eat like a fish!\n"; } };
class OtherAnimal : public Animal { };
int main() { Animal *anAnimal[4]; anAnimal[0] = new Animal(); anAnimal[1] = new Wolf(); anAnimal[2] = new Fish(); anAnimal[3] = new OtherAnimal();
for(int i = 0; i < 4; i++) anAnimal[i]->eat(); }
Output with the virtual method
Output without the virtual method
Pure virtual functions are also used where the method declarations are being used to define an interface for which derived classes will supply all implementations. An abstract class serving as an interface contains only pure virtual functions, and not any data members or ordinary methods. Use of purely abstract classes as interfaces works in C++ as it supports multiple inheritance. Because many OO languages do not support multiple inheritance they often provide a separate interface mechanism. This is seen in Java for example.
void Abstract::pure_virtual() { // do something }
class Child : Abstract { virtual void pure_virtual(); // no longer abstract, this class may be // instantiated. };
void Child::pure_virtual() { Abstract::pure_virtual(); // the implementation in the abstract class // is executed }
The compiler knows which method implementation to call at runtime by creating a table of pointers to all of the virtual functions in a class, called a
class A { public:
A() { } ~A() { std::cout << "Destroy A" << std::endl; } };
class B : public A { public:
B() { } ~B() { std::cout << "Destroy B" << std::endl; } };
int main() { A* b1 = new B; B* b2 = new B;
delete b1; // Only ~A() is called though b1 is an instance of class B // because ~A() is not declared virtual delete b2; // Calls destructors ~B() and ~A()
return 0; }
Output: Destroy A Destroy B Destroy A
Correctly declaring the destructor for class A as
Purpose
The concept of the virtual function solves the following problem:In OOP when a derived class inherits from 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 functions overridden by the derived class, a problem then arises when a derived object has been cast as the base class type. When a derived object is referred to as being of the base's type, the desired function call behavior is ambiguous.
The distinction between virtual and not virtual is provided to solve this issue. If the function in question is designated "virtual" 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.
Example
For example, a base classAnimal could have a virtual function eat. Subclass Fish would implement eat() differently than subclass Wolf, but you can invoke eat() on any class instance referred to as Animal, and get the eat() behavior of the specific subclass.
This allows a programmer to process a list of objects of class
Animal, telling each in turn to eat (by calling eat()), with no knowledge of what kind of animal may be in the list. You also do not need to have knowledge of how each animal eats, or what the complete set of possible animal types might be.
The following is an example in C++:
- include <iostream>
class Animal { public: virtual void eat() { cout << "I eat like a generic Animal.\n"; } };
class Wolf : public Animal { public: void eat() { cout << "I eat like a wolf!\n"; } };
class Fish : public Animal { public: void eat() { cout << "I eat like a fish!\n"; } };
class OtherAnimal : public Animal { };
int main() { Animal *anAnimal[4]; anAnimal[0] = new Animal(); anAnimal[1] = new Wolf(); anAnimal[2] = new Fish(); anAnimal[3] = new OtherAnimal();
for(int i = 0; i < 4; i++) anAnimal[i]->eat(); }
Output with the virtual method
eat:
I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a generic Animal.
Output without the virtual method
eat:
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
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 that is not abstract. Classes containing pure virtual methods are termed "abstract;" they cannot be instantiated directly, and 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 functiondoOperation(), 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 are also used where the method declarations are being used to define an interface for which derived classes will supply all implementations. An abstract class serving as an interface contains only pure virtual functions, and not any data members or ordinary methods. Use of purely abstract classes as interfaces works in C++ as it supports multiple inheritance. Because many OO languages do not support multiple inheritance they often provide a separate interface mechanism. This is seen in Java for example.
C++
In C++, pure virtual functions are declared using a special syntax [ = 0 ] as demonstrated below.
class B {
virtual void a_pure_virtual_function() = 0;
};
The pure virtual function declaration provides only the prototype of the method. Although an implementation of the pure virtual function is typically not provided in an abstract class, it may be included. Every non-abstract child class is still required to override the method, but the implementation provided by the abstract class may be called in this way:
void Abstract::pure_virtual() { // do something }
class Child : Abstract { virtual void pure_virtual(); // no longer abstract, this class may be // instantiated. };
void Child::pure_virtual() { Abstract::pure_virtual(); // the implementation in the abstract class // is executed }
The compiler knows which method implementation to call at runtime by creating a table of pointers to all of the virtual functions in a class, called a
vtable or virtual table.
Virtual Destructors
Object-oriented languages typically manage memory allocation and deletion automatically when objects are created and destroyed, however some object-oriented languages allow a custom destructor method to be implemented if desired. One such language is C++, and as illustrated in the following example, it is important for a C++ base class to have a virtual destructor to ensure that the destructor from the most derived class will always be called. In the example below having no virtual destructor, while deleting an instance of class B will correctly call destructors for both B and A, if deleted as an instance of B, an instance of B deleted via a pointer to its base class A will fail to call the destructor for B.- include <iostream>
class A { public:
A() { } ~A() { std::cout << "Destroy A" << std::endl; } };
class B : public A { public:
B() { } ~B() { std::cout << "Destroy B" << std::endl; } };
int main() { A* b1 = new B; B* b2 = new B;
delete b1; // Only ~A() is called though b1 is an instance of class B // because ~A() is not declared virtual delete b2; // Calls destructors ~B() and ~A()
return 0; }
Output: Destroy A Destroy B Destroy A
Correctly declaring the destructor for class A as
virtual ~A() will ensure that the destructor for class B is called in both cases with the example above.
See also
References
- C++ FAQ Lite Copyright © 1991-2006, Marshall Cline.
Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including inheritance, modularity, polymorphism, and encapsulation.
..... Click the link for more information.
..... Click the link for more information.
confusing or unclear for some readers.
Please help [ improve the article] or discuss these issues on the talk page. In object-oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods
..... Click the link for more information.
Please help [ improve the article] or discuss these issues on the talk page. In object-oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods
..... Click the link for more information.
This article or section may be confusing or unclear for some readers.
Please [improve the article] or discuss this issue on the talk page. This article has been tagged since April 2007.
..... Click the link for more information.
Please [improve the article] or discuss this issue on the talk page. This article has been tagged since April 2007.
..... Click the link for more information.
Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including inheritance, modularity, polymorphism, and encapsulation.
..... Click the link for more information.
..... Click the link for more information.
This article or section may be confusing or unclear for some readers.
Please [improve the article] or discuss this issue on the talk page. This article has been tagged since April 2007.
..... Click the link for more information.
Please [improve the article] or discuss this issue on the talk page. This article has been tagged since April 2007.
..... Click the link for more information.
In object-oriented programming, a subclass is a class that inherits some properties from its superclass.
You can usually think of the subclass as being "a kind of" its superclass, as in a "a Manx is a kind of cat", or "a square is a kind of rectangle":
..... Click the link for more information.
You can usually think of the subclass as being "a kind of" its superclass, as in a "a Manx is a kind of cat", or "a square is a kind of rectangle":
- A cat
..... Click the link for more information.
In BCPL family languages such as C++ and Java, a declaration specifies a variable's dimensions, identifier, type, and other aspects. It is used to announce the existence of a variable or function; this is important in many languages (such as C) which require variables to be
..... Click the link for more information.
..... Click the link for more information.
An interface defines the communication boundary between two entities, such as a piece of software, a hardware device, or a user. It generally refers to an abstraction that an entity provides of itself to the outside.
..... Click the link for more information.
..... Click the link for more information.
Multiple inheritance refers to a feature of some object-oriented programming languages in which a class can inherit behaviors and features from more than one superclass. This contrasts with single inheritance, where a class may inherit from only one superclass.
..... Click the link for more information.
..... Click the link for more information.
Multiple inheritance refers to a feature of some object-oriented programming languages in which a class can inherit behaviors and features from more than one superclass. This contrasts with single inheritance, where a class may inherit from only one superclass.
..... Click the link for more information.
..... Click the link for more information.
Java
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
C++
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
A virtual method table, virtual function table, dispatch table, or vtable, is a mechanism used in programming language implementations in order to support dynamic polymorphism, i.e., run-time method binding.
..... Click the link for more information.
..... Click the link for more information.
In object-oriented programming, inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined. The new classes, known as derived classes, take over (or inherit
..... Click the link for more information.
..... Click the link for more information.
In computer science, a superclass is a class from which other classes are derived. A superclass is also called a parent class. The classes that are derived from a superclass are known as child classes, derived classes, or subclasses.
..... Click the link for more information.
..... Click the link for more information.
virtual inheritance is a kind of inheritance that solves some of the problems caused by multiple inheritance (particularly the "diamond problem") by clarifying ambiguity over which ancestor class members to use.
..... Click the link for more information.
..... Click the link for more information.
An adjustor thunk (or adjuster thunk) is an implementation detail in some C++ compilers' implementations of virtual functions.
..... Click the link for more information.
External links
- MSDN: C++: Under the Hood
- The Old New Thing: Adjuster Thunks
..... Click the link for more information.
This article is copied from an article on Wikipedia.org - the free encyclopedia created and edited by online user community. The text was not checked or edited by anyone on our staff. Although the vast majority of the wikipedia encyclopedia articles provide accurate and timely information please do not assume the accuracy of any particular article. This article is distributed under the terms of GNU Free Documentation License.
Herod_Archelaus