c++ - 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?
解决方案
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).
推荐阅读
- php - 如何在 S3 的树枝文件中使用相对路径?
- rhel7 - Podman build 命令无法拉取镜像
- node.js - puppeteer 表单填写日期字段未填写年份
- google-sheets - 具有特定格式内容的表格上的过滤功能 google-sheets
- postgresql - 添加可为空的列是否存在表重写的情况?
- java - 如何在不覆盖当前内容的情况下写入文件,同时限制 Java 中的文件大小
- android - Flutter:没有虚拟方法 getLongVersionCode(),Sdk 29
- javascript - 如何在 SSR React 应用程序中以编程方式获取我的 Google 优化实验 ID?
- javascript - 创建 ms 团队应用程序中的 javascript 实现问题
- javascript - 没有得到第三个条件