Loading....
Coupon Accepted Successfully!

 

Virtual Functions In Derived Classes

We know that when functions are declared virtual in the base class, it is mandatory to redefine virtual functions in the derived class. The compiler creates VTABLES for the derived class and stores addresses of functions in it. In case the virtual function is not redefined in the derived class, the VTABLE of the derived class contains the address of the base class virtual function. Thus, the VTABLE contains addresses of all functions. Thus, it is not possible for a function to exist but for its address to not be present in the VTABLE. Consider the following program, which shows the possibility of a function existing but an address not being located in the VTABLE:
 

15.12 Write a program to redefine a virtual base class function in the derived class. Also, add a new member in the derived class. Observe the VTABLE.

#include<iostream.h>

#include<conio.h>

class A

{

public:

virtual void joy()

{

cout<<endl<<“In joy of class A”;

}

};

class B: public A

{

public:

void joy() {cout<<endl<<“In joy of class B”;}

void virtual joy2()

{

cout<<endl<<“In joy2 of class B”;

}

};

void main()

{

clrscr();

A *a1,*a2;

A a3;

B b;

a1=&a3;

a2=&b;

a1->joy();

a2->joy();

// a2->joy2(); // joy2 is not member of class A

}

OUTPUT
In joy of class A
In joy of class B
 
Explanation: In the above program, the base class A contains one virtual function joy(). In the derived class B, the function joy() is redefined and defines a new virtual function joy2(). Figure shows VTABLES created for the base and derived class.
 
a2->joy2();
 
The above statement will generate an error message. In the above statement, the pointer a2 is treated as only a pointer to the base class object. The function joy2() is not a member of base class A. Hence, it is not allowed to invoke the function joy2() using the pointer object a2. However, an address of the derived class is assigned to the base class pointer, and the compiler has no way to determine that we are working with a derived class object. The compiler avoids calling virtual functions present only in derived classes. In a hierarchical class organization of various levels, if it is essential to invoke a function at any level by using a base class pointer, then the function should be declared virtual in the base class.
 

Fig: VTABLES for base and derived class




Test Your Skills Now!
Take a Quiz now
Reviewer Name