您的位置:首页 > 其它

Virtual table

2020-05-11 04:08 441 查看

# Implementation

“An object’s virtual method table will contain the addresses of the object’s dynamically bound methods. Method calls are performed by fetching the method’s address from the object’s virtual method table. The virtual method table is the same for all objects belonging to the same class, and is therefore typically shared between them.

Typically, the compiler creates a separate virtual method table for each class. When an object is created, a pointer to this table, called the virtual table pointer, vpointer or VPTR, is added as a hidden member of this object. As such, the compiler must also generate “hidden” code in the constructors of each class to initialize a new object’s virtual table pointer to the address of its class’s virtual method table.” — wiki

“First, every class that uses virtual functions (or is derived from a class that uses virtual functions) is given its own virtual table. This table is simply a static array that the compiler sets up at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.

Second, the compiler also adds a hidden pointer to the base class, which we will call *__vptr. *__vptr is set(automatically) when a class instance is created so that it points to the virtual table for that class. Unlike the *this pointer, which is actually a function parameter used by the compiler to resolve self-references, *__vptr is a real pointer. Consequently, it makes each class object allocated bigger by the size of one pointer. It also means that *__vptr is inherited by derived classes, which is important.“ —learncpp

1.编译器为每一个有虚函数的类创建一张独立的虚函数表
2.虚函数表为每一个虚函数存储一个地址(虚函数地址
3.当对象被创建时,编译器会在构造函数中为该对象初始化一个指向虚函数表的指针(Default last or first member of the object
4.虚表指针不同于this指针,this指针是对自我的引用,存放的是当前对象的地址
  • “`By now, you’re probably confused as to how these things all fit together, so let’s take a look at a simple example:
class Base
{
public:
virtual void function1() {};
virtual void function2() {};
};

class D1: public Base
{
public:
virtual void function1() {};
};

class D2: public Base
{
public:
virtual void function2() {};
};

int main()
{
D1 d1;
Base *dPtr = &d1;    //reference the address of d1; D1's vtable;
dPtr->function1();   //lookup the address of function1 in vtable
}

First, the program recognizes that function1() is a virtual function. Second, the program uses dPtr->__vptr to get to D1’s virtual table. Third, it looks up which version of function1() to call in D1’s virtual table. This has been set to D1::function1(). Therefore, dPtr->function1() resolves to D1::function1()!

  • View of Example,just for reference:
PANHSDN 原创文章 4获赞 0访问量 905 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: