What is virtual function?

0 votes
34 views
Shikhar Arora asked 07-Dec-2019 in Technology by Shikhar Arora

What is virtual function

1 Answer

0 votes
Sangsaptak Pal answered 2 days ago by Sangsaptak Pal

Virtual function is a member function which is declared within a base class and re-defined or overwritten by a derived class. Virtual functions are declared in the base class with the keyword virtual. The resolving of the function call is done at run time. However there are certain rules that need to followed for virtual functions. These rules are as follows : 

  • Virtual functions can neither be static functions nor be the friend function of another class.
  • Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
  • The prototype of virtual functions should be same in base as well as derived class
  • A class may have virtual destructor but it cannot have a virtual constructor

For instance, suppose BIRD is a base class and PARROT is a derived class. Now beak is a virtual function in BIRD class which gets declared in BIRD class and gets defined in the PARROT class.