开发者

How does a C++ object access its member functions?

开发者 https://www.devze.com 2023-01-18 23:37 出处:网络
How does a C++ object know where it\'s member function definitions are present? I am quite confused as the Object itself does not contain the function pointers.

How does a C++ object know where it's member function definitions are present? I am quite confused as the Object itself does not contain the function pointers. 开发者_如何学Pythonsizeof on the Object proves this. So how is the object to function mapping done by the Runtime environment? where is a class's member function-pointer table maintained?


If you're calling non-virtual functions, there's no need for a function-pointer table; the compiler can resolve the function addresses at compile-time. So:

A a;
a.func();

translates to something along the lines of:

A a;
A_func(&a);

Calling a virtual function through a base-class pointer typically uses a vtable. So:

A *p_a = new B();
p_a->func();

translates to something along the lines of:

A *p_a = new B();
p_a->p_vtbl->func(p_a);

where p_vtbl is a compiler-implemented pointer to the vtable specific to the actual class of *p_a.


There are generally two ways that an object and its member functions are associated:

  • For a non-virtual function, the compiler determines the appropriate function at compile time. Non-static member functions are usually passed a hidden parameter that contains the this pointer, which takes care of the association of the object and the class member function.
  • For virtual functions, most compilers tend to use a lookup table that is usually referenced via the object's this pointer or a similar mechanism. This table, normally called the vtable, contains the function pointer for the virtual functions only.

As C++ is not a dynamic language, the compiler can do most of the object/function/symbol resolution at compile time with the exception of some virtual functions. In some cases, it's even possible for the compiler to determine exactly which instance of a virtual function gets called and skip the resolution via the vtable.


Member functions are not part of the object - they are defined statically, in one place, just like any other function. There is no magic look-up needed.

Virtual functions are different, but I don't think your question is about that...


For non-virtual functions there is one (global, per-class) function table which all instances use. Since it's the same for all of them - deterministic at compile-time - you would not want it duplicated in each instance.

For virtual functions, resolution is done at runtime and the object will contain a function table for them. Try that and look at your object again.

0

精彩评论

暂无评论...
验证码 换一张
取 消