Coupon Accepted Successfully!


Constructors And Virtual Functions

It is possible to invoke a virtual function using a constructor. A constructor makes the virtual mechanism illegal. When a virtual function is invoked through a constructor, the base class virtual function will not be called; instead, the member function of a similar class is invoked.

15.15 Write a program to call virtual function through constructor.



class B


int k;


B (int l) {k=l;}
virtual void show() {cout<<endl<<“ k=”<<k;}

class D: public B

int h;
D (int m, int n) : B (m)
B *b;
void show()
cout<<endl<<“ h=”<<h;

void main()

B b(4);
D d(5,2);



In the above program, the base class B contains a virtual function. In the derived class D, a similar function is redefined. Both the base and derived classes contain a constructor. In the derived class constructor, the base class pointer *b is declared. We know that this pointer contains the address of the object calling the member function. Here, the this pointer holds the address of the object d. The pointer object b invokes the function show(). The derived class show() function is invoked.
Here, the object d is not fully constructed; then, how does it invoke the member function of a similar class? This is possible, because a virtual function call reaches ahead into inheritance.

Test Your Skills Now!
Take a Quiz now
Reviewer Name