What is virtual function? Explain with an example.
- A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.
- Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked. But if we want to invoke derived class function using base class pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support runtime polymorphism.
- Consider the following program code :
a = 1;
virtual void show()
Class B: public A
b = 2;
virtual void show()
pA = &oB;
- Output is 2 since pA points to object of B and show() is virtual in base class A.
What are virtual functions?
Polymorphism is also achieved in C++ using virtual functions. If a function with same name exists in base as well as parent class, then the pointer to the base class would call the functions associated only with the base class. However, if the function is made virtual and the base pointer is initialized with the address of the derived class, then the function in the child class would be called.
What is virtual function?
Virtual function is the member function of a class that can be overriden in its derived class. It is declared with virtual keyword. Virtual function call is resolved at run-time (dynamic binding) whereas the non-virtual member functions are resolved at compile time (static binding).
Describe the virtual function and virtual function table.
A virtual function in C++ is :
- A simple member function of a class which is declared with “virtual” keyword
- It usually performs different functionality in its derived classes.
- The resolving of the function call is done at run-time.Virtual Table :
- A virtual table is a mechanism to perform dynamic polymorphism i.e., run time binging. Virtual table is used to resolve the function calls at runtime. Every class that uses virtual functions is provided with its own virtual functions.
- Every entry in the virtual table is a pointer that points to the derived function that is accessible by that class. A hidden pointer is added by a compiler to the base class which in turn calls *_vptr which is automatically set when an instance of the class is created and it points to the virtual table for that class.