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 program

 using namespace std;
 class shape{ public: virtual void draw()
{ cout<<"shapen";
 } }; class rectangle : public shape{ public: void draw()
{ cout<<"rectanglen";
 } }; class circle : public shape{ public: void draw()
{ cout<<"circlen"; } };
 class square : public shape{ public: void draw()
{ cout<<"squaren"; 
} }; int main(){ shape *bptr;
 rectangle r; bptr = &r;
 circle c; bptr = &c;
 bptr-> draw(); square s;
 bptr = &s;
 return 0; }


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

This article is written by our awesome writer
Comments to: Virtual function in Cpp with Simple Example

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories


Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page


Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
    Strength indicator
    Log In | Lost Password