|
Article on other languages:
|
In object-oriented programming, a virtual function or virtual method is one whose behavior 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 object-oriented programming (OOP).
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 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. ExampleFor example, a base class This allows a programmer to process a list of objects of class The following is an example in C++: #include <iostream.h> using namespace std; class Animal { public: virtual void eat() { cout << "I eat like a generic Animal." << endl; } }; class Wolf : public Animal { public: void eat() { cout << "I eat like a wolf!" << endl; } }; class Fish : public Animal { public: void eat() { cout << "I eat like a fish!" << endl; } }; class GoldFish : public Fish { public: void eat() { cout << "I eat like a goldfish!" << endl; } }; class OtherAnimal : public Animal { }; int main() { Animal* anAnimal[5]; anAnimal[0] = new Animal(); anAnimal[1] = new Wolf(); anAnimal[2] = new Fish(); anAnimal[3] = new GoldFish(); anAnimal[4] = new OtherAnimal(); for (int i = 0; i < 5; i++) { anAnimal[i]->eat(); delete anAnimal[i]; } return 0; } Output with the virtual method I eat like a generic Animal. I eat like a wolf! I eat like a fish! I eat like a goldfish! I eat like a generic Animal. Output if I eat like a generic Animal. I eat like a generic Animal. I eat like a generic Animal. I eat like a generic Animal. I eat like a generic Animal. JavaIn Java, all methods are by default "virtual functions". The following is an example in Java: public class Animal { public void eat() { System.out.println("I eat like a generic Animal."); } public static void main(String[] args) { Animal[] anAnimal = new Animal[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(); } } } public class Wolf extends Animal { public void eat() { System.out.println("I eat like a wolf!"); } } public class Fish extends Animal { public void eat() { System.out.println("I eat like a fish!"); } } public class OtherAnimal extends Animal {} Output: I eat like a generic Animal. I eat like a wolf! I eat like a fish! I eat like a generic Animal. Abstract classes and pure virtual functionsA 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 function 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 no 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 Abstract { public: virtual void pure_virtual() = 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 : public 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 } JavaIn Java, pure virtual methods are declared using the abstract keyword. Such a method cannot have a body. A class containing abstract methods (either directly, or inherited and not overridden) must itself be declared abstract. (But the converse is not true - an abstract class is not required to have any abstract methods.) An abstract class cannot be instantiated. abstract class B { abstract void a_pure_virtual_function(); } Java also uses interfaces. All of the methods declared in an interface are implicitly abstract: interface C { void a_pure_virtual_function(); } Behavior During ConstructionLanguages differ in their behaviour while the constructor of an object is running. For some languages, notably C++, the virtual dispatching mechanism is not used during construction as the invariants of derived classes are not yet set up and calling a method on such an object is risky. While it is recommended that virtual function calls in constructors should be avoided for C++ [1], in some other languages, for example Java and C#, 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. C++#include <iostream> #include <string> using namespace std; class Base { public: Base() { cout << "Constructing " << length() << endl; } virtual int length() const { return 0; } }; class Derived : public Base { string m_name; public: Derived(const string& name) : m_name(name.empty() ? "<default>" : name) // Member variable m_name is never empty {} virtual int length() const { return m_name.size(); } }; int main() { Derived("hi"); // Expected output: "Constructing 2" return 0; } Output: Constructing 0 Javapublic class Base { public int length() { return 0; } public Base() { System.out.println("Constructing " + length()); } static class Derived extends Base { String name_; public Derived(String name) { name_ = name != null ? name : ""; // Class invariant name_ is not null } public int length() { return name_.length(); } // Assume name_ is not null } public static void main(String[] args) { new Derived("Ooops"); // NullPointerException, Derived.name_ has not been assigned to yet } } This is because the constructor of Base is executed before the constructor of Derived. As the constructor of Base calls length(), a null pointer exception is thrown. Virtual destructorsObject-oriented languages typically manage memory allocation and deallocation 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 the object is 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> using namespace std; class A { public: A() { } ~A() { cout << "Destroy A" << endl; } }; class B : public A { public: B() { } ~B() { cout << "Destroy B" << endl; } }; int main() { A* b1 = new B; B* b2 = new B; delete b1; // According to the C++ standard, // the behaviour of this is undefined. // Usually, 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 See alsoReferences
|
This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License.
Mercedes Car
This site monitored by SitePinger.net