首页 > 解决方案 > How dose base pointer address in derived class?

问题描述

As I know that we could use base class pointer to address and call virtual functions in derived classes, because base class pointer has a more limited pointer scope. But I just want to know, how does base class pointer know where to start in derived class?

For example, for the record A, B and C all HAS there own data members, we can discuss this issue in two different categories 1. A, B & C all have their virtual functions; 2. A, B & C only have their own data members without any virtual functions

class A {...};
class B {...};
class C : public A, public B {...};

C c;
B* b = &c

Inside C, A should be placed over the top of B, so how does pointer b know where to start addressing in C?

标签: c++pointersinheritancememory

解决方案


The compiler knows the layout, so it will emit code, which will calculate the address of the B subobject in C.

Let's see a simple actual example:

class A { int x; };
class B { int y; };
class C: public A, public B { };

B *get(C &c) {
    return &c;
}

In get, the compiler must calculate where B resides in C. Here's an example of the compiled code (godbolt):

get(C&):                              # @get(C&)
        lea     rax, [rdi + 4]
        ret

This means that the compiler will add 4 bytes to the address of the input argument (c), and returns that (it adds 4, because sizeof(A) is 4, and the compiler decided to not add any additional padding).

Note, that if A is empty, then it is likely that the address of B is the same as C. And if A is not empty (has non-static data members, or has virtual functions), then B's address will likely differ. But all these are implementation details, depends on the platforms ABI (Application Binary Interface).


推荐阅读