6

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?

JJJ
  • 32,902
  • 20
  • 89
  • 102
UnTraDe
  • 3,747
  • 10
  • 36
  • 60

3 Answers3

2

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?

Community
  • 1
  • 1
Marcello Romani
  • 2,967
  • 31
  • 40
  • And what about the c++ case? Both of them should look in the same structure or memory layout in the end no? There can be more than one way to do this? Because for example you can have this struct with the functions as well but I thinm it's unlikely because it costs more memory if objects duplicate the same functions over ans over. – UnTraDe May 19 '13 at 11:45
  • Write a "hallo world" C program. Compile it with gcc -o hw hw.c. Issue objdump -d hw. It's the same story, what changes are just the tools names and the specific instructions. IOW the target cpu is different: it's virtual in .net, real in C++. – Marcello Romani May 19 '13 at 11:52
1

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.

Steve Waddicor
  • 2,197
  • 15
  • 20
0

All the object oriented-ness in OOP is just a higher level programming construct to enable developer to write modular and organized code in a paradigm containing prototypes and their instances. oop code doesn't have its equivalent in machine code .

Its more like how we have interfaces in typescript which then translates to javascript which doesn't have the concept of interfaces. (this may not be a very good example)