Assembly Language for Beginners

(Jeff_L) #1

3.18. C++


lea ecx, DWORD PTR _b$[esp+40]
call ??0box@@QAE@HHHH@Z ; box::box
push 40
push 2
lea ecx, DWORD PTR _s$[esp+32]
call ??0sphere@@QAE@HH@Z ; sphere::sphere
lea ecx, DWORD PTR _b$[esp+24]
call ?print_color@object@@QAEXXZ ; object::print_color
lea ecx, DWORD PTR _s$[esp+24]
call ?print_color@object@@QAEXXZ ; object::print_color
lea ecx, DWORD PTR _b$[esp+24]
call ?dump@box@@QAEXXZ ; box::dump
lea ecx, DWORD PTR _s$[esp+24]
call ?dump@sphere@@QAEXXZ ; sphere::dump
xor eax, eax
add esp, 24
ret 0
_main ENDP


The inherited classes must always add their fields after the base classes’ fields, to make it possible for
the base class methods to work with their own fields.


When theobject::print_color()method is called, a pointers to both theboxandsphereobjects are
passed asthis, and it can work with these objects easily since thecolorfield in these objects is always
at the pinned address (at offset+0x0).


It can be said that theobject::print_color()method is agnostic in relation to the input object type as
long as the fields arepinnedat the same addresses, and this condition is always true.


And if you create inherited class of theboxclass, the compiler will add the new fields after thedepthfield,
leaving theboxclass fields at the pinned addresses.


Thus, thebox::dump()method will work fine for accessing thecolor,width,heightanddepthsfields,
which are always pinned at known addresses.


The code generated by GCC is almost the same, with the sole exception of passing thethispointer (as it
has been explained above, it is passed as the first argument instead of using theECXregister.


Encapsulation


Encapsulation is hiding the data in theprivatesections of the class, e.g. to allow access to them only from
this class methods.


However, are there any marks in code the about the fact that some field is private and some other—not?


No, there are no such marks.


Let’s try this simple example:


#include <stdio.h>


class box
{
private:
int color, width, height, depth;
public:
box(int color, int width, int height, int depth)
{
this->color=color;
this->width=width;
this->height=height;
this->depth=depth;
};
void dump()
{
printf ("this is box. color=%d, width=%d, height=%d, depth=%d\n", color, width, ⤦
Çheight, depth);
};
};

Free download pdf