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 + +