Oops Class Test
Oops Class Test
Part B
4. What are virtual functions? Explain their needs using a suitable example. What are the rules associated with virtual
functions? (16)
Virtual Function:
A virtual function is a function in a base class that is declared using the keyword virtual.
- 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 functions 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.
1
- 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.
Rules for Virtual Function:
1. The virtual function should not be static and must be a member of a class.
2. The virtual function may be declared as a friend for another class. An object pointer can access the virtual functions.
3. A constructor cannot be declared as virtual, but a destructor can be declared as virtual.
4. The virtual function should be defined in the public section of the class. It is also possible to define the virtual function outside the
class. In such a case, the declaration is done inside the class, and the definition is outside the class. The virtual keyword is used in the
declaration and not in the function declarator.
5. It is also possible to return a value from virtual functions similar to other functions.
6. The prototype of the virtual function in the base class and derived class should be exactly the same. In case of a mismatch, the
compiler neglects the virtual function mechanism and treats these functions as overloaded functions.
7. Arithmetic operations cannot be used with base class pointers.
8. If a base class contains a virtual function and if the same function is not redefined in the derived classes, in such a case, the base
class function is invoked.
9. The operator keyword used for operator overloading also supports the virtual mechanism.
#include <iostream>
using namespace std;
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.\n"; }
};
class D1 : public B
{
public:
void display()
{ cout<<"Content of first derived class.\n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.\n"; }
};
int main()
{
B *b;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this code here because the function of base class is virtual. */
b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}