Inherit object model
? The inner class of the C + + compiler can be understood as a struct
? Subclasses are the new members of the parent class that are superimposed on the child class.
On the model of "sample Code" inheriting object
1#include <iostream>2#include <string>3 4 using namespacestd;5 6 classDemo {7 protected:8 intmi;9 intMJ;Ten Public: One Virtual voidprint () { Acout <<"mi ="<< mi <<", " -<<"MJ ="<< MJ <<Endl; - } the }; - - classDerived: PublicDemo { - intMk; + Public: -Derived (intIintJintk) { +Mi =i; AMJ =J; atmk =K; - } - - voidprint () { -cout <<"mi ="<< mi <<", " -<<"MJ ="<< MJ <<", " in<<"mk ="<< Mk <<Endl; - } to }; + - //proving that the derived memory arrangement is the same as the test class the structTest { * void*p; $ intmi;Panax Notoginseng intMJ; - intMk; the }; + A intMainintargcConst Char*argv[]) { thecout <<"sizeof (Demo) ="<<sizeof(Demo) <<Endl; +cout <<"sizeof (Derived) ="<<sizeof(Derived) <<Endl; - $Derived D (1,2,3); $test* p = reinterpret_cast<test*> (&d); - -cout <<"before changing ..."<<Endl; the - d.print ();Wuyi theP->mi =Ten; -P->MJ = -; WuP->MK = -; - Aboutcout <<"After changing ..."<<Endl; $ - d.print (); - - return 0; A}Polymorphic Object Model
C + + polymorphism implementation principle:
? When a virtual function is declared in a class, the compiler generates a virtual function table in the class
? A virtual function table is a data structure that stores the address of a member function
? Virtual function tables are automatically generated and maintained by the compiler.
? The virtual member function is placed in the virtual function table by the compiler
? When there is a virtual function table, there is a pointer to the virtual function table in each object
void int v) { P-and add (v);}
Does the compiler confirm that add () is a virtual function?
- The yes--> compiler looks for the address of the Add () in the virtual function table that the object vptr points to
- No--the compiler can directly determine the address of the member function being called
51-c++ Object Model analysis (bottom)