Assembly Language for Beginners

(nextflipdebug2) #1

3.18. C++


int main()
{
class c c1;
class c c2(5,6);


c1.dump();
c2.dump();

return 0;
};


MSVC: x86


Here is how themain()function looks like, translated into assembly language:


Listing 3.81: MSVC

_c2$ = -16 ; size = 8
_c1$ = -8 ; size = 8
_main PROC
push ebp
mov ebp, esp
sub esp, 16
lea ecx, DWORD PTR _c1$[ebp]
call ??0c@@QAE@XZ ; c::c
push 6
push 5
lea ecx, DWORD PTR _c2$[ebp]
call ??0c@@QAE@HH@Z ; c::c
lea ecx, DWORD PTR _c1$[ebp]
call ?dump@c@@QAEXXZ ; c::dump
lea ecx, DWORD PTR _c2$[ebp]
call ?dump@c@@QAEXXZ ; c::dump
xor eax, eax
mov esp, ebp
pop ebp
ret 0
_main ENDP


Here’s what’s going on. For each object (instance of classc) 8 bytes are allocated, exactly the size needed
to store the 2 variables.


Forc1adefaultargumentlessconstructor??0c@@QAE@XZiscalled. Forc2anotherconstructor??0c@@QAE@HH@Z
is called and two numbers are passed as arguments.


Apointertotheobject(thisinC++terminology)ispassedintheECXregister. Thisiscalledthiscall(3.18.1)—
the method for passing a pointer to the object.


MSVC does it using theECXregister. Needless to say, it is not a standardized method, other compilers can
do it differently, e.g., via the first function argument (like GCC).


Why do these functions have such odd names? That’sname mangling.


A C++ class may contain several methods sharing the same name but having different arguments—that
is polymorphism. And of course, different classes may have their own methods with the same name.


Name manglingenable us to encode the class name + method name + all method argument types in one
ASCII string, which is then used as an internal function name. That’s all because neither the linker, nor
the DLLOSloader (mangled names may be among the DLL exports as well) knows anything about C++
orOOP^23.


Thedump()function is called two times.


Now let’s see the constructors’ code:


Listing 3.82: MSVC

_this$ = -4 ; size = 4
??0c@@QAE@XZ PROC ; c::c, COMDAT


(^23) Object-Oriented Programming

Free download pdf