Considering following code snippet, fun( ) of which class would get called and why?


#include
class base
{

public :

virtual void fun( )
{

cout << "base class's fun..." <<>

}
base( )
{

fun( ) ;

}

} ;

class derived : public base
{

public :

derived( )
{

fun( ) ;

}
void fun( )
{

cout << "derived class's fun..." <<>

}

} ;

void main( )
{

derived d ;

}

Ans: First, the fun( ) of base class and then fun( ) of derived class would get called. While constructing the object d of derived class, first the base class constructor would get called. At this moment, the VTABLE would hold the address of base class version of virtual function fun( ). As a result fun( ) of base gets called. The moment control reaches derived class’s constructor the VTABLE would now hold the address of its version of virtual function fun( ) as a result fun( ) of derived class gets called.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>