C++ Virtual Functions

PREV     NEXT

What are C++ virtual functions?

  • When the same function name is used in both base and derived classes, then the function in base class is declared as virtual using the keyword virtual before the declaration of the function.
  • When you declare a function as virtual then C++ tells which function is to be used at runtime but based on the type of object pointed to the base pointer, rather than the type of the pointer.
  • The virtual function is a member function of a class and it is declared in a base class and overridden in a derived class so, when we point to a derived class so, when we point to a derived class object using a pointer to the base class, then a virtual function for that object is called and executes the derived class of that function.
  • The virtual keyword is used to declare the virtual function. It is used to tell the compiler to perform dynamic linkage or late binding on the function.

Let us have a look at the example:

Some rules for Virtual Functions in C++:

  • The virtual functions must be declared in the public section of the class.
  • They are always defined in base class and overridden in derived class but it is not mandatory to override in derived class.
  • The virtual functions should be accessed using pointer to achieve run time polymorphism.
  • They cannot be static and friend function also cannot be the virtual function of another class.

PREV     NEXT

Share this website !!!
Facebook Twitter Linkedin