[英]How does the compiler call a Derived member function, when I use a member function pointer defined in terms of the Base class?
The code below works, but I'm not quite sure I understand why the member function pointer memfunc_ptr
ends up pointing to the correct function Derived::member_func()
(see example here ). 下面的代码有效,但是我不太确定我为什么理解成员函数指针
memfunc_ptr
最终指向正确的函数Derived::member_func()
(请参见此处的示例)。 I know that a member function pointer defines an offset into the class of the object, for which it's defined, in this case class Base
. 我知道成员函数指针定义了要为其定义对象的类的偏移量 ,在本例中为
Base
类。 So, to justify the result obtained by the code, ie, that the member function Derived::member_func
is called, instead of Base::member_func
, I have to conclude that this offset is applied to the vtable of the class Derived
, as member_func()
is virtual, and the object d
is of class Derived
. 因此,为了证明代码获得的结果的合理性,即调用成员函数
Derived::member_func
而不是Base::member_func
,我必须得出结论,此偏移量作为member_func()
应用于类Derived
的vtable member_func()
是虚拟的,而对象d
是Derived
的类。 Does that make sense? 那有意义吗?
#include <iostream>
class Base {
public:
virtual void member_func() {
std::cout << "Base" << '\n'; };
};
class Derived : public Base {
public:
virtual void member_func() { std::cout << "Derived" << '\n'; };
};
int main() {
typedef void (Base::*MFP)();
MFP memfunc_ptr;
memfunc_ptr = &Base::member_func;
Derived d;
(d.*memfunc_ptr)();
}
member_func()
is a virtual function. member_func()
是一个虚函数。 The compiler will hence always call the most appropriate function for the real type of the object that is pointed to. 因此,编译器将始终为所指向的对象的实际类型调用最合适的函数。 The way this is ensured is implementation specific .
确保这一点的方法是特定于实现的 。
The most frequently way to do it is to use a vtable , a table of funtion pointers. 最常用的方法是使用vtable(函数指针表)。 A pointer to the vtable is initialised during the construction of the object.
指向vtable的指针在对象构造期间初始化。 Every time you refer to such a virtual function, the compiler will generate code to find the function pointer in the vtable (using an ofset in the vtable).
每次引用这样的虚函数时,编译器都会生成代码以在vtable中查找函数指针(使用vtable中的偏移量)。 And when you use a pointer to a virtual function, the compiler will generate code to find the right pointer in the vtable.
当使用指向虚拟函数的指针时,编译器将生成代码以在vtable中找到正确的指针。
This article will show you how this work with more details. 本文将详细介绍如何进行此工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.