Virtual function table and function table in C ++
(Thanks http://blog.csdn.net/haoel/article/details/1948051)
The role of virtual functions in C ++ is to implement the polymorphism mechanism.
Polymorphism. In short, a pointer of the parent type is used to point to the instance of its subclass, and then the member function of the actual subclass is called through the pointer of the parent class. This technology enables the pointer of the parent class to have multiple forms. This is a generic technology.
Virtual functions are implemented through a Virtual Table (V-Table. This table records the address table of a class virtual function. This table solves the inheritance and overwrite problems. The C ++ compiler should ensure that the pointer of the virtual function table exists in the front of the object instance. Therefore, when we use the pointer of the parent class to operate a subclass, this virtual function table, like a map, specifies the actually called function.
Suppose there is a base class:
1 class Base {2 public:3 virtual void f() { cout << "Base::f" << endl; }4 virtual void g() { cout << "Base::g" << endl; }5 virtual void h() { cout << "Base::h" << endl; }6 };
There is a node at the end of the virtual function table, which is the end node of the virtual function table, just like the string Terminator "/0", marking the end of the virtual function table.
1 typedef void (* Fun) (void); 2 Base B; 3 Fun pFun = NULL; 4 5 cout <"virtual function table address:" <(int *) (& B) <endl; 6 cout <"virtual function table-first function address:" <(int *) * (int *) (& B) <endl; 7 8 // Invoke the first virtual function 9 pFun = (Fun) * (int *) (& B )); 10 pFun (); 11 12 (Fun) * (int *) (& B) + 0); // Base: f () 13 (Fun) * (int *) (& B) + 1); // Base: g () 14 (Fun) * (int *) (& B) + 2); // Base: h ()
You can forcibly convert & B to int * to obtain the address of the virtual function table. Then, you can obtain the address of the first virtual function, that is, Base :: f ().
General inheritance (no virtual function overwrite)
The subclass does not load any function of the parent class. The following table lists the virtual functions of instance Derive d:
1) virtual functions are stored in the table in the declared order.
2) the virtual function of the parent class is prior to the virtual function of the subclass.
General inheritance (with virtual function overwrite)
If there is a virtual function in the subclass, the virtual function of the parent class is reloaded.
1) The f () function to be overwritten is placed at the original parent class virtual function in the virtual table.
2) The unoverwritten functions remain.