1#include <iostream>2 using namespacestd;3 classbase14 {5 intA;6 Doubleb;7 CharC;8 };9 intMain ()Ten { One base1 B; A return 1; -}
vs Output Class Layout method : First select the left side of the c/c++-> command line, and then write the other options here/d1 reportallclasslayout, it can see all the related classes of memory layout, if written on/d1 Reportsingleclasslayoutxxx (XXX is the class name), only the memory layout of the specified class XXX will be typed.
Base1 Memory Layout
1#include <iostream>2 using namespacestd;3 classAnimal4 {5 protected:6 intAge ;7 Public:8 Virtual voidPrint_age (void) =0;9 };Ten classDog PublicAnimal One { A Public: -Dog () { This->age =2;} -~Dog () {} the Virtual voidPrint_age (void) {cout<<"wang,my age ="<< This->age<<Endl;} - }; - classCat PublicAnimal - { + Public: -Cat () { This->age =1;} +~cat () {} A Virtual voidPrint_age (void) {cout<<"miao,my age ="<< This->age<<Endl;} at }; - intMainvoid) - { - cat Kitty; - dog JD; -Animal *PA; in int*p = (int*) (&kitty); - int*q = (int*) (&JD); top[0] = q[0]; +cout<<p[1]<<Endl; -cout<<q[1]<<Endl; thePA = &Kitty; *PA-print_age (); $System"Pause");Panax Notoginseng return 0; - the}
Memory layout:
This memory structure is divided into two parts, the memory distribution, the following is the virtual table, we look at one by one. VS has the compiler to place the virtual table pointer at the beginning of the memory (0 address offset), and then the member variable, the following generated a virtual table, immediately after the &[classname]_meta of the 0, the virtual table corresponding to the virtual pointer in memory distribution, the following list of virtual functions, The left 0 is the ordinal of this virtual function, there is only one virtual function, so there is only one, if there are more than one virtual function, there will be a sequence number 1, the virtual function of 2 is listed.
The compiler creates this virtual table pointer and the virtual table in the constructor function.
So how does the compiler use virtual table pointers and virtual tables to achieve polymorphism? So, when you create an object that contains a parent of a virtual function, the compiler points the virtual table pointer to the virtual function of the parent class when the object is constructed, and similarly, when the object of the subclass is created, the compiler will set the virtual table pointer in the constructor (the subclass has only one virtual table pointer, It comes from the parent class) that points to the virtual table of the subclass (the virtual function entry address inside the virtual table is a subclass).
Output Result:
C++class Memory Layout