C + + object model
There are two concepts that can explain the C + + object model:
The part of the language that directly supports object-oriented programming.
The underlying implementation mechanism for various support.
Single Inheritance (parent class with virtual function)
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 class Base 6 {7 Public : 8 void Fun1 () {cout << "Base fun1" << Endl;} 9 virtual void fun2 () {cout << "Base fun2" << Endl;} Private : int a;12 };13 class Derive:public Base15 {public : + void fun1 () { cout << "Derive fun1" << Endl;} void Fun2 () {cout << "Derive fun2" << Endl;} Private : $ int b;21 };22 int main () { base b;26 Derive d;27 base *p = & d;28 p-> fun1 (); p-> fun2 (); System ("Pause" ); return 0 ; span>
Output: The base class pointer p dynamically binds at run time, Fun2 calls the subclass method, fun1 The parent class method is still called because there is no virtual
Memory model:
The virtual table of the pointer points to the subclass method address
In order to support a polymorphic mechanism, the compiler adds a virtual function pointer (vptr) to the class when a class itself defines a virtual function, or if its parent class has a virtual function. Virtual function pointers are generally placed in the first position of the object's memory layout, in order to ensure that the virtual function table can be taken with maximum efficiency in the case of multi-level inheritance or multiple inheritance.
When VPRT is at the front of the object's memory, the address of the object is the virtual function pointer address.
Virtual inheritance
C + + object model: Single inheritance, multiple inheritance, virtual inheritance