Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does object oriented code translate into machine code?

How exactly does the oop code that I write in C++ or C# for example translate into machine code or in the case of C# into bytecode? I mean, how do the objects translate?

In procedural programming it's pretty obvious how it looks like after compilation because there is acually a real support for functions in the machine language. But in the case of oop programing there are no objects in machine language.

My theory is that it compiles the object itself to some sort of C like struct which contains only data (no member functions) and when a memeber function is called, if accepts an addional parameter which is the data struct of the object itself. Am I right?

like image 674
UnTraDe Avatar asked Oct 22 '22 09:10

UnTraDe


2 Answers

No need to guess, just look at the generated "assembly" (MSIL, in fact) code:

How can I view MSIL / CIL generated by C# compiler? Why is it called assembly?

like image 119
Marcello Romani Avatar answered Oct 25 '22 20:10

Marcello Romani


It's implementation dependant. But in practice, the common thing is to use a virtual table ("vtable"). There's a virtual table for each class, which contains a list of pointers to the implementation of each member function. Each object gets a pointer to the appropriate vtable.

Depending on the language and compiler flags, the appropriate pointer in the vtable may be looked up by function signature (name and arguments) or simply by an index.

When the member-function is called via it's vtable pointer, for sure it needs a pointer to the object data. But that might be passed on the stack or in a register.

like image 41
Steve Waddicor Avatar answered Oct 25 '22 20:10

Steve Waddicor