Where is the memory of fn() locate?
Since it's a normal function, somewhere in the code section of your program. This location is the same for all instances of the class. In fact, it has got nothing to do with the instantiation of B
via pb
.
Is there a pointer in object that pointing at the memory loaction of fn()?
No. For a normal member function this isn't required since the address is known at compile time (or, at the latest, at link time); it therefore doesn't have to be stored separately at runtime.
For virtual functions, the situation is different. Virtual function pointers are stored in an array (called “virtual function-pointer table” or “vtable” for short). Each class has one such vtable and each instance to a class stores a pointer to that vtable. This is necessary because if a pointer/reference of type Base
points to a sub-class Derived
, the compiler has no way of knowing which function to call; rather, the correct function is calculated at runtime by looking it up in the associated vtable. The vtable pointer is also evident in the sizeof
the object.