1. Derived class objects can be cast to base class objects
#include <iostream>using namespace Std;class base{public:int a;base (int x=0): A (x) {}void print () {Cout<<a <<endl;}}; Class Son:public Base{public:char Y;son (char x): Y (x) {}operator double () {return 1.3423;} void print () {cout<<y<<endl;}}; int main () {son V ('-');((base) v). Print ();cout<< (double) v <<endl;cin.get (); return 0;}
The cast type can be defined by itself, such as operator double () to customize the type conversion.
Son V ('-'); 0041140E push 2Dh //Temp variable 00411410 Lea Ecx,[v]//Take offset address 00411413 call son:: Son (4110EBh)//Use the destination address to invoke the Son::son constructor base B (1); 00411418 push 1 //Temp variable 0041141A Lea ecx,[b]// Bend offset Address 0041141D call Base::base (411104h)//Use destination address to invoke Base::base constructor B.print (); 00411422 Lea ecx,[ b]//Take the offset address of B 00411425 call Base::p rint (4110FFH)//Use the destination address to invoke base::p rint Output function ((base) v). Print (); 0041142A mov eax,dword ptr [v]//V-directed content is passed to eax0041142d mov dword ptr [EBP-0E4H],EAX///Exa content is put into a new memory space, Not free storage 00411433 Lea ecx,[ebp-0e4h]//Fetch storage space offset address 00411439 call Base::p rint (4110FFH)//Calling the print function , the default new memory space is the base object (double) v;0041143e Lea Ecx,[v] 00411441 call son::operator double (411140h)// Call type conversion function to convert 00411446 fstp St (0)
The forced type conversion of the default derived class to the base class is a direct read of the memory (some people think that the constructor of the derived class is called, the temporary base class object is constructed, and if so, it can only be said that a part of the constructor is called, or that the memory copy is more directly in place).
C + + inheritance casts