Detailed description of the application of the C ++ virtual function table and the Function Application
We know that the private method of the class is to be called in C ++. We can use the friend method. However, if we know the definition of a class, we can directly call its private function based on the memory layout of the Class Object.
As a follow-up article on the implementation principle of C ++ virtual functions, this article does not intend to introduce the memory layout of classes, this article only describes how to use a virtual function table to call private virtual functions of this class.
The following Test class provides a private virtual function virtual void Func ():
Class Test {public: Test () {} virtual ~ Test () {} private: virtual void Func () {printf ("Private Function \ n ");}};
Now we use the virtual function table to call the Func member function:
Typedef void (* PFN_Func) (); int main () {Test t; unsigned long ** VirtualTable = (unsigned long **) (& t ); unsigned long FuncAddr = VirtualTable [0] [1]; PFN_Func pfnFunc = (PFN_Func) FuncAddr; if (pfnFunc) {pfnFunc ();} return 0 ;}
We know that the virtual function table is actually a two-dimensional array. Because the Test class in the example does not inherit from other classes, the first dimension has only one element. Because the Test class has two virtual functions, the second dimension has two elements, therefore, VirtualTable [0] [1] is used to obtain the Func function address.
Because this example runs in the MSVC compiler environment, the virtual function table is considered to be at the starting position of the Class Object Memory layout by default. Therefore, the unsigned long ** VirtualTable = (unsigned long **) is used directly **) (& t );.
A rigorous approach should be to first determine whether the virtual function table is at the starting position of the memory layout.