c++ virtual function called in constructor
Hello I have one question in c++. I have a base class B and this has a virtual function f1( )
and d1, d2 and d3 are the derived classes of the B. Only d3 overrides the virtual function.
Question : from my B constructor i need to call the function f1( ). For the objects of type d1 and d2 i expect the base class
versions virtual function be called where as for the objects d3 i am expecting the d3 version of the virtual function being excecuted.
Class B
{
public:
B( ) { f1( ); }
virtual void f1( ) { //d1 ,d2 and base use this code}
}
Class d1 : public B
{
}
Class d1 : public B
{
}
Class d3 : public B
{
virtual f1( ) { //d3 specific code }
}
main( )
{
B *b1 = new d1( ); /*I expect the base version of the f1() would be called */
B *b3 = new d3( ); /*I expect the base version of the f1() would be called */
}
Can some body please help me in solving this.
I know when a constructor calls a virtual function , only the current class virtual function would be called. In this case
only base f1( ) version would be called even for the b3 object.
Re: c++ virtual function called in constructor