Virtual function in C++ with Simple Example


Virtual means existing in appearance but not in reality, when virtual functions are used, a program that appears to be calling a function of one class may, in reality, be calling a function a different class. Virtual functions are without a doubt the most difficult concept for the new C++ programmer to understand. However, they are also the turning point in the understanding of object-oriented programming. If you don't use virtual functions, you don't understand object-oriented programming yet.

When the same function name is used in both base and derived classes, the function base class is declared as virtual using the keyword virtual preceding its normal declaration. When the function is made virtual C++ determines the type of function to be used at the run-time depending upon the type of object rather than the type of pointer. In this way, the base pointer can be made to point to different objects thereby allowing execution of various versions of virtual functions.

Program For Virtual function in C++ with Simple Example

#include<iostream> using namespace std; class shape{ public: virtual void draw(){ cout<<"shape\n"; } }; class rectangle : public shape{ public: void draw(){ cout<<"rectangle\n"; } }; class circle : public shape{ public: void draw(){ cout<<"circle\n"; } }; class square : public shape{ public: void draw(){ cout<<"square\n"; } }; int main(){ shape *bptr; rectangle r; bptr = &r; bptr->draw(); circle c; bptr = &c; bptr-> draw(); square s; bptr = &s; bptr->draw(); return 0; }

Output:-

rectangle
circle
square

Explanation of the program

The rule here is that the Compiler selects the function to be called based on the contents of the pointer bptr, and not on the data type of the pointer(only if the function is virtual). This selection is made during the execution of the program because how does Compiler know which function to link when it doesn't know which object's address bptr is going to contain at runtime. It could be the address of an object of the rectangle class or of the circle class or of the square class