C++ Virtual Functions Summary

Virtual functions are C++’s way of implementing polymorphism.

  • What is polymorphism? Polymorphism is often viewed as the third pillar of object-oriented programming after encapsulation and inheritance. To give a simple example, if we have a class Animal, and classes like Chicken and Dog that inherit from Animal, and they respond differently to the same message derived from the parent class Animal. For instance, the Animal class has an action “makeSound()”, while the Chicken class would “crow()” and the Dog class would “bark()” - this is called polymorphism. According to Wikipedia, polymorphism can be defined as “the ability to associate different specific behaviors with a single generalized notation.” It refers to when a computer program runs, the same message may be sent to objects of different classes, and the system can trigger corresponding class methods based on the object’s class, resulting in different behaviors. Simply put, polymorphism means that the same message given to different objects triggers different actions.

Virtual functions enable dynamic polymorphism, which is determined at runtime. Only during program execution does the system decide whether to call the base class or child class function. The system determines which function to call based on the object that the base class pointer points to.

  • How to declare a virtual function? Add the virtual keyword before the declaration to declare a virtual function. The function is declared in the parent class and implemented in the child class.

  • What is a pure virtual function? A pure virtual function is a function that is assigned a value of 0 when declaring a virtual function. After using this declaration method, the inheriting class must implement this virtual function.

  • How are virtual functions implemented? Through a virtual table (vtable). Each object has a virtual table pointer that points to the virtual table. The virtual table is essentially an array, not a linked list. The addresses of virtual functions are stored in the virtual table in the order of declaration.

  • How is the virtual function table implemented? To accomplish the functionality of virtual functions, the compiler (note, this is why C++ is sometimes called compiler-oriented programming) creates a table for each class that declares internal virtual functions, called a vtable. In the vtable, the addresses of virtual functions of specific types are placed in the order of declaration. Each class with virtual functions contains a pointer, called a vpointer or vptr, pointing to this vtable. Whenever a call to a class’s virtual function occurs, the compiler redirects to call the function in the vtable pointed to by this vptr, rather than statically calling a specific function.

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy