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,

  1. if declare method virtual compiler knows method has evaluated @ runtime. method must invoked using pointer or reference.
  2. 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

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -