Share to: share facebook share twitter share wa share telegram print page

Virtual function

In object-oriented programming such as is often used in C++ and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method that is dispatched dynamically. Virtual functions are an important part of (runtime) 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, treat all methods as virtual by default[1][2] 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[3] and PHP[4]).

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 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 (linked) 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 is 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 selected according to the declared type of the pointer or reference.

Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code is compiled.[citation needed]

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 function matching, and overriding as dynamic function mapping.

Example

C++

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 behavior of the specific subclass.

class Animal {
 public:
  // Intentionally not virtual:
  void Move() {
    std::cout << "This animal moves in some way" << std::endl;
  }
  virtual void Eat() = 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() 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.

In C, the mechanism behind virtual functions could be provided in the following manner:

#include <stdio.h>

/* an object points to its class... */
struct Animal {
    const struct AnimalVTable *vtable;
};

/* which contains the virtual function Animal.Eat */
struct AnimalVTable {
    void (*Eat)(struct Animal *self); // 'virtual' function 
};

/*
   Since Animal.Move is not a virtual function
   it is not in the structure above.
*/
void Move(const struct Animal *self) {
    printf("<Animal at %p> moved in some way\n", ( void* )(self));
}

/*
   unlike Move, which executes Animal.Move directly,
   Eat cannot know which function (if any) to call at compile time.
   Animal.Eat can only be resolved at run time when Eat is called.
*/
void Eat(struct Animal *self) {
    const struct AnimalVTable *vtable = *( const void** )(self);
    if (vtable->Eat != NULL) { 
        (*vtable->Eat)(self); // execute Animal.Eat
    } else {
        fprintf(stderr, "'Eat' virtual method not implemented\n");
    }
}

/*
   implementation of Llama.Eat this is the target function 
   to be called by 'void Eat(struct Animal *self).'
*/
static void _Llama_eat(struct Animal *self) {
    printf("<Llama at %p> Llama's 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) {
   /* init objects as instance of its class */
   struct Animal animal = { &Animal };
   struct Animal llama = { &Llama };
   Move(&animal); // Animal.Move
   Move(&llama);  // Llama.Move
   Eat(&animal);  // cannot resolve Animal.Eat so print "Not Implemented" to stderr
   Eat(&llama);   // resolves Llama.Eat and executes
}

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 cannot 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 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.[5][6]

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.

Behavior during construction and destruction

Languages differ in their behavior while the constructor or 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.[7]: §15.7.3 [8][9] If that function is a pure virtual function, then undefined behavior occurs.[7]: §13.4.6 [8] This is true even if the class contains an implementation for that pure virtual function, since a call to a pure virtual function must be explicitly qualified.[10] A conforming C++ implementation is not required (and generally not able) to detect indirect calls to pure virtual functions at compile time or link time. Some runtime systems will issue a pure virtual function call error when encountering a call to a pure virtual function at run time.

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).[11] Some 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 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.

See also

References

  1. ^ "Polymorphism (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)". docs.oracle.com. Retrieved 2020-07-11.
  2. ^ "9. Classes — Python 3.9.2 documentation". docs.python.org. Retrieved 2021-02-23.
  3. ^ "Writing Final Classes and Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)". docs.oracle.com. Retrieved 2020-07-11.
  4. ^ "PHP: Final Keyword - Manual". www.php.net. Retrieved 2020-07-11.
  5. ^ Pure virtual destructors - cppreference.com
  6. ^ "abc — Abstract Base Classes: @abc.abstractmethod"
  7. ^ a b "N4659: Working Draft, Standard for Programming Language C++" (PDF).
  8. ^ a b Chen, Raymond (April 28, 2004). "What is __purecall?".
  9. ^ Meyers, Scott (June 6, 2005). "Never Call Virtual Functions during Construction or Destruction".
  10. ^ Chen, Raymond (October 11, 2013). "C++ corner case: You can implement pure virtual functions in the base class".
  11. ^ Ganesh, S.G. (August 1, 2011). "Joy of Programming: Calling Virtual Functions from Constructors".

Read other articles:

Polish ski jumper Jakub WolnyWolny at the 2019 World Championships in SeefeldCountry PolandBorn (1995-05-15) 15 May 1995 (age 28)Bielsko-Biała, PolandSki clubLKS Klimczok BystraPersonal best237.5 m (779 ft)Planica, 23 March 2019World Cup careerSeasons2014–presentTeam wins3Team podiums3Indiv. starts87 Medal record Men's ski jumping World Junior Championship 2014 Val di Fiemme Individual NH 2014 Val di Fiemme Team NH Updated on 26 March 2021. Jaku...

 

هذه المقالة بحاجة لصندوق معلومات. فضلًا ساعد في تحسين هذه المقالة بإضافة صندوق معلومات مخصص إليها. يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (يناير 2022) هذه المق

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (ديسمبر 2022) النحت في عصر النهضة الإيطاليةمعلومات عامةأحد أوجه إيطاليا البلد إيطاليا التأثيراتفرع من النحت في عصر النهضة — Italian sculpture (en) — Italian Renaissance art (en) تعديل - تعديل م

For the other MTR station in Mong Kok, see Mong Kok station. Yaumati station redirects here. For the other MTR station, see Yau Ma Tei station. MTR station in Kowloon, Hong Kong 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.Find sources: Mong Kok East station – news · newspapers · books · scholar · JSTOR (February 2015)...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يونيو 2020) حزب القلعة الشعبي الوطني الإندونيسي البلد إندونيسيا  تاريخ التأسيس 2002  المقر الرئيسي جاكرتا  تعديل مصدري - تعديل   حزب القلعة الشعبي الوطني الإندو�...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أغسطس 2019) (242450) 2004 QY2 موقع الاكتشاف مرصد سايدنغ سبرينغ  تاريخ الاكتشاف 20 أغسطس 2004  الأسماء البديلة 2004 QY2  فئةالكوكب الصغير كويكبات أبولو  الحضيض 0.566676441014225 وحدة...

Elegi KeagunganAlbum kompilasi karya KompilasiDirilis1991GenrePopLabelProsound Elegi Keagungan merupakan sebuah album kompilasi yang dirilis pada tahun 1991. Berisi 12 lagu pilihan. Lagu utamanya di album ini ialah Jam Kehidupan dari dua kakak beradik keluarga Noorsaid, Lydia & Imaniar. Daftar lagu Jam Kehidupan (Lydia Kandou & Imaniar) Akhirnya (Younky Soewarno & Deddy Dhukun) Tuhan Ada Dimana Mana (Dodo Zakaria & James F. Sundah) Ada Satu Milyard (Yono Slalu) Buat Kau (B...

 

2001 studio album by GotthardHomerunStudio album by GotthardReleased17 January 2001 (2001-01-17)Length48:47LabelBMGProducer Chris von Rohr Leo Leoni Gotthard chronology Open(1999) Homerun(2001) Human Zoo(2003) Homerun is the fifth studio album by Swiss hard rock band Gotthard. It was released on 17 January 2001 through BMG. The album peaked at #1 in the Swiss charts and was certified as 3× Platinum for exceeding 90,000 sales. This is Gotthard's best-selling album. It h...

 

Igneous mountain in the state of Colorado Tomichi DomeTomichi Dome viewed from U.S. Route 50Highest pointElevation11,471 ft (3,496 m)[1][2]Prominence2,325 ft (709 m)[2]Isolation10.74 mi (17.28 km)[2]ListingColorado prominent summitsCoordinates38°29′06″N 106°31′44″W / 38.4849944°N 106.5289192°W / 38.4849944; -106.5289192[3]GeographyTomichi DomeColorado LocationGunnison County, Colorad...

Article principal : Tir à l'arc aux Jeux olympiques d'été de 2012. Londres 2012 - Par équipes femmes Généralités Sport Tir à l'arc Organisateur(s) CIO Édition 6e Lieu(x) Londres Date 27 et 29 juillet 2012 Nations 12 Participants 36 athlètes Site(s) Lord's Cricket Ground Palmarès Tenant du titre Corée du Sud Vainqueur Corée du Sud Deuxième Chine Troisième Japon Navigation Pékin 2008 Rio de Janeiro 2016 modifier L'épreuve par équipes féminine de tir à l'arc des Jeux oly...

 

Former building originally in Hyde Park, London, 1854 relocated to Sydenham, South London The Crystal PalaceThe Crystal Palace at Sydenham (1854)General informationStatusDestroyedTypeExhibition palaceArchitectural styleVictorianTown or cityLondonCountryUnited KingdomCoordinates51°25′21″N 0°04′32″W / 51.4226°N 0.0756°W / 51.4226; -0.0756Completed1851Destroyed30 November 1936Cost£80,000 (1851)(£12 million in 2022)Design and constructionArchitect(s)Joseph Pa...

 

1957 South Korean filmTwilight TrainKorean poster for Twilight Train (1957)Hangul황혼열차Hanja黃昏列車Revised RomanizationHwang yeolchaMcCune–ReischauerHwanghon yŏlch‘a Directed byKim Ki-youngWritten byIm Hee-jaeLee Kwang-suProduced byChoe Jae-ikStarringPark AmDo Kum-bongChoi SamCinematographySim Jae-heungEdited byKim Ki-youngMusic byHan Sang-kiDistributed byDong-kwang FilmsRelease date October 31, 1957 (1957-10-31) CountrySouth KoreaLanguageKorean Twilight Train (...

Indian author and speaker This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Rabi Maharaj – news · newspapers · books · scholar · JSTOR (February 2017) (Learn how and when to remove this template message)...

 

Чирський Микола АнтоновичНародження 18 лютого 1902(1902-02-18)Кам'янець-Подільськ, Російська імперіяСмерть 26 лютого 1942(1942-02-26) (40 років)Кам'янець-Подільськ, Кам'янець-Подільська область, Українська РСР, СРСРтуберкульозКраїна  УНРПриналежність  Армія УНРЗвання хорунжийВійн...

 

飛行第4戦隊創設 1938年(昭和13年)8月31日廃止 1945年(昭和20年)所属政体 大日本帝国所属組織 大日本帝国陸軍部隊編制単位 戦隊兵種/任務/特性 航空作戦(偵察)(空中戦闘)編成地 芦屋町通称号/略称 天風35001最終上級単位 第12飛行師団最終位置 山口県 下関市主な戦歴 日中戦争-第二次世界大戦テンプレートを表示 飛行第4戦隊(ひこうだいよんせんたい、飛行第四戰...

Television film directed by Corey Allen The Man in the Santa Claus SuitGenreDramaScreenplay byGeorge KirgoStory byLeonard GersheDirected byCorey AllenStarringFred AstaireGary BurghoffJohn BynerBert ConvyMajel BarrettMusic byPeter MatzCountry of originUnited StatesOriginal languageEnglishProductionExecutive producersDick ClarkAl Schwartz (executive producer)ProducerLee MillerCinematographyWoody OmensEditorLovel EllisRunning time104 minutesProduction companyDick Clark ProductionsOriginal releas...

 

Lian Ross Lian Ross en un concierto Polonia (2010)Información personalNombre de nacimiento Josephine Hiebel Nacimiento 8 de diciembre de 1962 (60 años)Hamburgo (Alemania Occidental) Nacionalidad AlemanaFamiliaCónyuge Luis Rodríguez Salazar Información profesionalOcupación CantanteAños activa desde 1979Género Pop Hi-NRG Euro discoInstrumento Voz Sitio web lianross.com[editar datos en Wikidata] Josephine Hiebel (8 de diciembre de 1962, Hamburgo), conocida artísticamente como ...

 

Questa voce o sezione sull'argomento centri abitati della Spagna non cita le fonti necessarie o quelle presenti sono insufficienti. Puoi migliorare questa voce aggiungendo citazioni da fonti attendibili secondo le linee guida sull'uso delle fonti. Segui i suggerimenti del progetto di riferimento. Mediana de Voltoyacomune Mediana de Voltoya – Veduta LocalizzazioneStato Spagna Comunità autonoma Castiglia e León Provincia Ávila TerritorioCoordinate40°42′02.16″N 4°33�...

Il Papiro di Brooklyn 35.1446 rinvenuto a Tebe,[1] è un documento egizio risalente alla XIII dinastia che contiene un lungo elenco di nomi di servitori della corte di Khutawy,[2] con il loro grado ed i compiti ripartiti tra uomini e donne.[3] Papiro di Brooklyn - Morso di Serpente (Foto: 47.218.48_47.218.85) Il papiro cita anche il visir Ankhu che assieme ai suoi funzionari riceve in dono, per ordine del sovrano, del cibo[2] e tra i vari argomenti viene citata...

 

2016 United States House of Representatives elections in Arizona ← 2014 November 8, 2016 (2016-11-08) 2018 → All 9 Arizona seats to the United States House of Representatives   Majority party Minority party   Party Republican Democratic Last election 5 4 Seats won 5 4 Seat change Popular vote 1,266,088 1,078,620 Percentage 51.55% 43.92% Swing 4.13% 4.54% Republican   50–60%   60–70%   70–80%...

 
Kembali kehalaman sebelumnya