virtual function Implementation Mechanism of C + +

Source: Internet
Author: User

The implementation mechanism of virtual functions in C + + is mainly vtable and virtual pointers. Details are as follows:


Class A {

Public

virtual void F1 ();

virtual void F2 ();

Private

int A;

}


Class B {

Public

void F1 ();

Private

int b;

}


such as a, B, two classes, the compiler prepares a virtual table for Class A Vtablea as follows:

A::F1 's address
A::F2 's address

The compiler prepares the Vtableb for Class B as follows:

B::F1 's address
A::F2 's address

Class B overrides the F1, so the entry address of B::F1 () is recorded in the vtable of Class B, and F2 is inherited from a, so F2 still uses the A::F2 's entry address.

When you define b b = new B (), the compiler allocates space and assigns a virtual pointer vptr to the vtable that points to B.


So when using the following statement:

A *pa = &b; PA->F1 ();

The compiler knows that F1 is a virtual member function whose entry address is placed in the first item of the table, so it is converted to call* (PA->VPTR) [0]. This is the entry address where the B::F1 is placed.

The polymorphism is realized.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

virtual function Implementation Mechanism of C + +

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.