1) 理解如何通过virtual fuction table指向正确的方法;
Typically, the compiler creates a separate vtable for each class. When an object is created, a pointer to this vtable, called the virtual table pointer, vpointer or VPTR, is added as a hidden member of this object (becoming its first member unless it's made the last[2]). The compiler also generates "hidden" code in the constructor of each class to initialize the vpointers of its objects to the address of the corresponding vtable.
也就是说不同的子类其vtable指向的方法是不同的,这就是用vtable实现的多态。
2) 理解子类看上去像基类是如何实现的?(thunks)
Consider the following C++ code:
D *d = new D();
B1 *b1 = static_cast<B1*>(d);
B2 *b2 = static_cast<B2*>(d);
While d
and b1
will point to the same memory location after execution of this code, b2
will point to the location d+8
(eight bytes beyond the memory location of d
). Thus, b2
points to the region within d
which "looks like" an instance of B2
, i.e., has the same memory layout as an instance of B2
.
用thunks实现的面向接口编程。客户端只需要知道接口而不需要知道后面的实现类。