c++ - How derived object in base pointer invokes base function? -
how can base pointer holding derived object still point base function ? here after
a_ptr = &b_obj; a_ptr->disp();
if base function had been virtual understand involvement of v-table, holds address base function.but here base pointer hodling derived object can manage call base function.
can throw light on happens behind scene ?
class { public: //virtual void disp() void disp() { cout<< "from class a\n" << endl; } }; class b : public { public: void disp() { cout << "from class b\n" <<endl; } }; int main() { a_obj; *a_ptr; b b_obj; a_ptr = &a_obj; a_ptr->disp(); a_ptr = &b_obj; a_ptr->disp(); }
base pointer points base part of derived object. doesn't know information derived object members / methods.
if declare method a::disp()
virtual
, resolved @ runtime. may call a::disp()
or b::disp()
based on object a_ptr
points to.
in simple words,
- if declare method
virtual
compiler knows method has evaluated @ runtime. method must invoked using pointer or reference. - if method called using object or if method not
virtual
compiler straight away puts call method of static type of caller.
in case, static type of caller a*
, method not virtual
. compiler straight away put call a::disp()
; doesn't wait runtime evaluation.
a_ptr = &b_obj; // static type --> typeof(*a_ptr) --> // dynamic type --> typeof(b_obj) --> b a_ptr->disp(); // (is a::disp() virtual)? // chooses b::disp() @ runtime : chooses a::disp() @ compiletime;
[note: suppose if make b::disp()
virtual
, keep a::disp()
normal method is, still same results getting now.]
Comments
Post a Comment