Loading....
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.

#include<iostream.h>

#include<constream.h>

class B

{

int k;

public:

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

};
class D: public B
{

int h;
public:
D (int m, int n) : B (m)
{
h=n;
B *b;
b=this;
b->show();
}
void show()
{
cout<<endl<<“ h=”<<h;
}

};
void main()
{

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

}

OUTPUT
h=2


Explanation:
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