In this blog, I assume that you have a basic background about C++ and know that there is a “monster” we call it as
virtual table :)
If there is virtual member function in your class’s definition, there will be a virtual table.
Compiler will generate a pointer which’s name is
_vprt and use this pointer to find the virtual table.
The function below there is very important for us to understand the C++ object model.
get_element take the reference of object which’s type is T(I used template technology) and
We get the address of this object by
&obj and then we cast it into pointer which point to unsigned long and then we dereference that pointer. Acctually, the pointer which we dereferenced in function
get_element is the
After we get
_vprt, we cast it into
unsigned long* again and add
offset to get others pointers in virtual table which contains all pointers that point to class virtual member functions.
If we dereference the return value of this function, we will get the pointer which point to the begin of function. Fantastic :)
First of all, let’s take a glance at this demo:
There are data member
prv_data with different access label in
class base. There also have virtual functions and normal member functions in this class. So … what’s the memory model of this class look like?
The output of that demo:
The inheritance relationship between the base class and derived class :
It’s single inheritance that base class must be only single type.
We find that:
The virtual table pointer _vprt is at the beginning of the object.
Data member store into object and have nothing with the access label but according to the sequence of declaration.
In single inheritance model, the virtual function wichi is re-implement will be update in all virtual table.
Now, you find that there is only one virtual table in our object under single inheritance situation. But … How about things going on with multiply inheritance(MI) ?
Let’s go and test it.
We can declare some conclusions that:
Each base class have their own’s virtual table. Assume that The number of base class is N in multiple inheritance. The number of the virtual table is N-1.The virtual table of derived function will be combine into the first base class in the declaration queue of base class.
The base virtual table will be update if the derived class rewrite implementation of virtual function in base class.
You find that The base object was inherited again and again Output:
It’s may not what we want that the base class is inherited repeatedly. So C++ use the
virtual base technology to solve this problem :)
It’s a hard time to draw this picture. But thank god… I make it.
ATTENTION: Every class in C++ only have ONE virtual table, different objects of the same class will share the same virtual table of that class!
Photo by Jason Leaster images
作者: Jason Leaster
本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可