Reputation: 37
I know that calling a virtual function from constructor/destructor resolves to an early binding. But I have a question here. Look at the below code
class Base
{
public:
virtual void fun()
{
cout<<"In Base"<<endl;
}
};
class Derived : public Base
{
public:
Derived(Base obj)
{
Base *p;
p = &obj;
p->fun();
}
void fun()
{
cout<<"In Derived"<<endl;
}
};
int main()
{
Base b;
Derived d(b);
}
O/P is : In Base
My doubt here is, that compiler might be using dynamic binding instead of early binding. Please correct me i am wrong but i need a clear explanation of how compiler performs an early binding inside a constructor?
If the method is not a constructor the compiler will convert this statement p->fun in to something like
fetch the VPTR at run time (This vptr will have the derived class VTABLE address)
invoke method at vptr + offset
hence the right virtual function is invoked.
but since it is a constructor, does compiler stop considering the virtual mechanism and simnply forget about the pointer type and replace the above statement p->fun() to obj.fun() (internally treating it as invoking with the appropriate object)
Because even if you do early binding or late binding the result is same(invoking the local fun() )
Also if it is the local version of the function that is invoked as per the early binding mechanism inside a constructor, then how are we invoking Base version of the function which is not local to the derived (I understand derived contains base sub object but need to know the reason behind calling the base version rather than the local/derived function if the constructor performs an early binding inside a constructor for virtual functions)
Please help
Upvotes: 0
Views: 211
Reputation: 29266
Because you are passing an actual Base
to the creator (not a pointer or a reference) what you have there is an actual Base
instance - casting the pointer to to Derived*
is not valid.
Upvotes: 2