How is inheritance implemented at the memory level?

前端 未结 5 1123
无人共我
无人共我 2021-02-13 15:36

Suppose I have

class A           { public: void print(){cout<<\"A\"; }};
class B: public A { public: void print(){cout<<\"B\"; }};
class C: public A         


        
5条回答
  •  遥遥无期
    2021-02-13 16:09

    In your example here, there's no copying of anything. Generally an object doesn't know what class it's in at runtime -- what happens is, when the program is compiled, the compiler says "hey, this variable is of type C, let's see if there's a C::print(). No, ok, how about A::print()? Yes? Ok, call that!"

    Virtual methods work differently, in that pointers to the right functions are stored in a "vtable"* referenced in the object. That still doesn't matter if you're working directly with a C, cause it still follows the steps above. But for pointers, it might say like "Oh, C::print()? The address is the first entry in the vtable." and the compiler inserts instructions to grab that address at runtime and call to it.

    * Technically, this is not required to be true. I'm pretty sure you won't find any mention in the standard of "vtables"; it's by definition implementation-specific. It just happens to be the method the first C++ compilers used, and happens to work better all-around than other methods, so it's the one nearly every C++ compiler in existence uses.

提交回复
热议问题