c++ - Why does base class pointer always point to base class even if it holds a derived class object address? -


i have gone through of previous posts on same issue couldn't find satisfying answer. why base class pointer point base class if holds address of derived class's object? know that, because of reason, virtual keyword came picture, couldn't figure out why base class pointer points base class if hold address of derived class. explain ?

class base {   public:void fn()   {     cout << "i in base" << endl;   } };  class derived : public base {   public:void fn()   {     cout << "i in derived"<< endl;   } };  int main() {   base *p;     // creating pointer object base class   derived obj; // creating object derived class   p=&obj;      // storing object of derived class in pointer   p->fn();     // if pointer has address of derived class object                // why still print base class function                // why need use virtual keyword print                // derived class function? } 

an object of derived class contains object of base class type somewhere inside it. called "base class subobject". if p has type base*, when p set point object of type derived, set point base subobject of derived object.

this behaviour ensures base class non-static member functions can called pointers when point object of derived class. because of this, implementation doesn't have up, @ runtime, whether p points complete base object or complete derived object; no matter what, it's still pointing base object (which might happen base class subobject).

in order ensure derived class's implementation of function called though used pointer base class, compiler has generate additional code look up, @ runtime, whether pointer points complete base object or complete derived object. if want force this, mark function virtual. if not, c++ not force pay cost virtual calls when don't need them.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -