Virtual functions in C++ are a key concept in object-oriented programming. They allow derived classes to provide a different implementation of a function declared in the base class. In other words, virtual functions provide a mechanism for late binding, which is the process of linking a function call to the actual function to be executed at run time.
The "virtual" keyword is used to declare a virtual function in the base class. When a virtual function is called through a reference or pointer to the base class, the actual function called will be the one defined in the derived class. This is known as dynamic dispatch or runtime polymorphism.
C++ Program to Demonstrate the Use of Virtual Functions
#include <iostream> using namespace std; class Shape { public: virtual void draw() { cout << "Drawing a Shape" << endl; } }; class Circle : public Shape { public: void draw() { cout << "Drawing a Circle" << endl; } }; class Square : public Shape { public: void draw() { cout << "Drawing a Square" << endl; } }; int main() { Shape *shape; Circle circle; Square square; shape = &circle; shape->draw(); shape = □ shape->draw(); return 0; }Output
Drawing a Circle Drawing a Square
In this program, we have created a base class Shape with a virtual function draw(). The draw() function simply outputs a message "Drawing a Shape". We have then created two derived classes Circle and Square, each with its own implementation of the draw() function.
In the main function, we have created pointers to Shape objects and assigned them to instances of the derived classes. When we call the draw() function through the base class pointer, it calls the implementation of the draw() function in the derived class. This demonstrates the use of virtual functions to dynamically dispatch a function call at run time.