3.18. C++
o1->dump();
o2->dump();
return 0;
};
Classobjecthas a virtual methoddump()that is being replaced in the inheritingboxandsphereclasses.
If we are in an environment where it is not known the type of an object, as in themain()function in exam-
ple, where the virtual methoddump()is called, the information about its type must be stored somewhere,
to be able to call the relevant virtual method.
Let’s compile it in MSVC 2008 with the/Oxand/Ob0options and see the code ofmain():
_s$ = -32 ; size = 12
_b$ = -20 ; size = 20
_main PROC
sub esp, 32
push 30
push 20
push 10
push 1
lea ecx, DWORD PTR _b$[esp+48]
call ??0box@@QAE@HHHH@Z ; box::box
push 40
push 2
lea ecx, DWORD PTR _s$[esp+40]
call ??0sphere@@QAE@HH@Z ; sphere::sphere
mov eax, DWORD PTR _b$[esp+32]
mov edx, DWORD PTR [eax]
lea ecx, DWORD PTR _b$[esp+32]
call edx
mov eax, DWORD PTR _s$[esp+32]
mov edx, DWORD PTR [eax]
lea ecx, DWORD PTR _s$[esp+32]
call edx
xor eax, eax
add esp, 32
ret 0
_main ENDP
A pointer to thedump()function is taken somewhere from the object. Where could we store the address
of the new method? Only somewhere in the constructors: there is no other place since nothing else is
called in themain()function.^28
Let’s see the code of the constructor of theboxclass:
??_R0?AVbox@@@8 DD FLAT:??_7type_info@@6B@ ; box `RTTI Type Descriptor'
DD 00H
DB '.?AVbox@@', 00H
??_R1A@?0A@EA@box@@8 DD FLAT:??_R0?AVbox@@@8 ; box::`RTTI Base Class Descriptor at (0,-1,0,64)'
DD 01H
DD 00H
DD 0ffffffffH
DD 00H
DD 040H
DD FLAT:??_R3box@@8
??_R2box@@8 DD FLAT:??_R1A@?0A@EA@box@@8 ; box::`RTTI Base Class Array'
DD FLAT:??_R1A@?0A@EA@object@@8
??_R3box@@8 DD 00H ; box::`RTTI Class Hierarchy Descriptor'
DD 00H
DD 02H
DD FLAT:??_R2box@@8
??_R4box@@6B@ DD 00H ; box::`RTTI Complete Object Locator'
DD 00H
DD 00H
(^28) You can read more about pointers to functions in the relevant section:(1.27 on page 384)