What are Virtual functions in C++ ?

  • Virtual function is a member function which is re-defined by a derived class and declared within a base class.
  • When you refer to a derived class object using a reference or pointer to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
  • It ensures that the correct function is called for an object, regardless of the type of reference used for function call.
  • It is mainly used to achieve Run-time polymorphism.
  • In base class functions are declared with a virtual. At run time the resolving of function call is done.

Sample Code

[pastacode lang=”cpp” manual=”using%20namespace%20std%3B%0A%20%0Aclass%20base%20%7B%0Apublic%3A%0A%20%20%20%20virtual%20void%20print()%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20cout%20%3C%3C%20%22print%20base%20class%5Cn%22%3B%0A%20%20%20%20%7D%0A%20%0A%20%20%20%20void%20show()%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20cout%20%3C%3C%20%22show%20base%20class%5Cn%22%3B%0A%20%20%20%20%7D%0A%7D%3B%0A%20%0Aclass%20derived%20%3A%20public%20base%20%7B%0Apublic%3A%0A%20%20%20%20void%20print()%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20cout%20%3C%3C%20%22print%20derived%20class%5Cn%22%3B%0A%20%20%20%20%7D%0A%20%0A%20%20%20%20void%20show()%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20cout%20%3C%3C%20%22show%20derived%20class%5Cn%22%3B%0A%20%20%20%20%7D%0A%7D%3B%0A%20%0Aint%20main()%0A%7B%0A%20%20%20%20base%20*bptr%3B%0A%20%20%20%20derived%20d%3B%0A%20%20%20%20bptr%20%3D%20%26d%3B%0A%20%0A%20%20%20%20%2F%2F%20Virtual%20function%2C%20binded%20at%20runtime%0A%20%20%20%20bptr-%3Eprint()%3B%0A%20%0A%20%20%20%20%2F%2F%20Non-virtual%20function%2C%20binded%20at%20compile%20time%0A%20%20%20%20bptr-%3Eshow()%3B%0A%20%20%20%0A%20%20%20%20return%200%3B%0A%7D%0A” message=”” highlight=”” provider=”manual”/]

Output

Leave a Reply

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