How derived object in base pointer invokes base function?
How can a base pointer holding derived object still point to base function ? Here After
a_ptr = &b_obj;
a_ptr->disp();
If the base function had been virtual i understand the involvement of V-table, which holds the address to base function.But here the base pointer hodling derived object can manage to call the base function.
Can anyone throw some light on what happens behind the scene ?
class A
{
p开发者_StackOverflow中文版ublic:
//virtual void disp()
void disp()
{ cout<< "From class A\n" << endl; }
};
class B : public A
{
public:
void disp()
{ cout << "From Class B\n" <<endl; }
};
int main()
{
A a_obj;
A *a_ptr;
B b_obj;
a_ptr = &a_obj;
a_ptr->disp();
a_ptr = &b_obj;
a_ptr->disp();
}
Base pointer always points to the base part of derived object. It doesn't know any information about Derived object members / methods.
If you declare the method A::disp()
as virtual
, then only it will be resolved at runtime. It may call A::disp()
or B::disp()
based on the object a_ptr
points to.
In simple words,
- If you declare a method
virtual
then compiler knows that this method has to be evaluated at runtime. Also the method must be invoked using pointer or reference. - If the method is called using an object or if the method is not
virtual
then compiler straight away puts the call to the method of the static type of the caller.
In your case, the static type of the caller is A*
and the method is not virtual
. Thus compiler straight away put the call for A::disp()
; it doesn't wait for runtime evaluation.
a_ptr = &b_obj; // static type --> typeof(*a_ptr) --> A
// dynamic type --> typeof(b_obj) --> B
a_ptr->disp(); // (is A::disp() virtual)?
// chooses B::disp() at runtime : chooses A::disp() at compiletime;
[Note: Suppose if you make only B::disp()
as virtual
and keep A::disp()
normal method as it is, then you will still get the same results as you are getting now.]
精彩评论