InterviewSolution
Saved Bookmarks
| 1. |
When the constructor of a base class calls a virtual function, why doesn't the override function of the derived class gets called? |
|
Answer» While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class WOULD get called. This is illustrated in the following example. #include <iostream> class base { PROTECTED : int i ; public : base ( int ii = 0 ) { i = ii ; show( ) ; } virtual void show( ) { cout << "base's show( )" << endl ; } } ; class derived : public base { private : int j ; public : derived ( int ii, int jj = 0 ) : base ( ii ) { j = jj ; show( ) ; } void show( ) { cout << "derived's show( )" << endl ; } } ; void main( ) { derived dobj ( 20, 5 ) ; }The output of this program would be: base's show( ) derived's show( ) |
|