How Vtable of Virtual functions work

2019-02-17 22:43发布

问题:

I have a small doubt in Virtual Table, whenever compiler encounters the virtual functions in a class, it creates Vtable and places virtual functions address over there. It happens similarly for other class which inherits. Does it create a new pointer in each class which points to each Vtable? If not how does it access the Virtual function when the new instance of derived class is created and assigned to Base PTR?

回答1:

Each time you create a class that contains virtual functions, or you derive from a class that contains virtual functions, the compiler creates a unique VTABLE for that class.

If you don’t override a function that was declared virtual in the base class, the compiler uses the address of the base-class version in the derived class.

Then it places the VPTR into the class. There is only one VPTR for each object when using simple inheritance . The VPTR must be initialized to point to the starting address of the appropriate VTABLE. (This happens in the constructor.) Once the VPTR is initialized to the proper VTABLE, the object in effect “knows” what type it is. But this self-knowledge is worthless unless it is used at the point a virtual function is called. When you call a virtual function through a base class address (the situation when the compiler doesn’t have all the information necessary to perform early binding), something special happens. Instead of performing a typical function call, which is simply an assembly-language CALL to a particular address, the compiler generates different code to perform the function call.



回答2:

For each class with virtual functions, a vtable is created. Then, when an object of a class with a viable is created using a constructor, the constructor copies the appropriate vtable into the object. So each object has a pointer to its vtable ( or in the case of multiple inheritance, when necessary, a Orr to each of its vtables. ). The compiler knows where in the object the vtable is, so when it needs to call a virtual method, it outputs byte code to deterrence the vtable, lookup the appropriate method, and jump to its address.

In the simple case of single inheritance, a child class starts with a copy of the parent class's vtable and then gets an overridden entry for each virtual method in the child class that overrides a parent class's method. ( and it also gets a new entry for every virtual function in the child clad that does not override a parent class method )



回答3:

Whenever the program compiles the virtual table for each class is created, which makes clear to the fact that vtables are created per class basis. During run time, when the object is created the compiler assigns vptr to the object, which points to the virtual table for the particular class' object. In short the vptr is created per object basis.