Virtual Functions

Definition

  • Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. It is essention to implement runtime polymorphism.

  • Write a program with virtual functions:

    • A base class and a derived class.
    • A function with same name in base class and derived class.
    • A pointer or reference of base class type pointing or referring to an object of derived class.

An Example

#include<iostream>
using namespace std;

class Base {
public:
    virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base {
public:
    void show() { cout<<"In Derived \n"; } 
};

int main(void) {  
    // a base class pointer
    Base *bp = new Derived;     
    bp->show();  // RUN-TIME POLYMORPHISM
    return 0;
}
Output:
In Derived
  • The derived class function is called using a base class pointer.

Why?

With virtual function, we can create a list of base class pointers and call methods of any of the derived classes without even knowing kind of derived class object. [aka polymorphism]

How?

  • vtable: A table of function pointers. It is class specific.
  • vptr: A pointer to vtable. It is object specific.
    http://quiz.geeksforgeeks.org/happens-virtual-function-called-inside-non-virtual-function/

  • Compiler does two things to use vptr and vtable.

    1. When constructing an object, compiler sets vptr of the object, pointing to vtable of the class.
    2. When a polymorphic call is made, compiler (1) uses base class pointer to look for vptr; (2) once vptr is fetched, it can get access to vtable of derived class ; (3)call the function in the derived class with vtable.

results matching ""

    No results matching ""