Detailed description of the application of the C ++ virtual function table and the Function Application

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.