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?
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With