A virtual function in CPP is used to perform dynamic linkage or late binding on a function. Late binding is used to resolve a function call during runtime, thus allowing the compiler to bind the function call at runtime after determining the type of object. A virtual function can be simply understood as a member function in base class which is redefined in a derived class and is declared using the virtual keyword.
Example:
#include <iostream.h> using namespace std; class Base { public: virtual void print() { cout << "Hey, I am the Base."<<endl; } }; class Derived:public Base { public: void print() { cout << "Hey, I was Derived."<<endl; } }; int main() { Base* b; Derived d; b = &d; b->print(); } |
Output
Hey, I was Derived. |