Home > OS >  How are object properties accessed internally?
How are object properties accessed internally?

Time:07-16

In reference to this question: How are variable names stored in memory in C?

It is explained that in C, the compiler replaces variable names from code with actual memory addresses.

Let's take C . I wonder how object properties are accessed in that context?

obj.prop

So obj gets replaced by the actual memory address. Does the compiler then replace prop with some sort of offset and add it to obj - ultimately replacing the whole expression with an absolute address?

CodePudding user response:

For simple cases and hiding the language lawyer hat:

obj.prop is *(&obj &Obj::prop). The the second part is a member pointer, which is basically the offset of the property inside the object.

The compiler can replace that with an absolute address if it knows the address of the obj at compile time. Assuming it has an obj in memory at all. The obj could be kept completely in registers. Or only parts of the obj may exist at all. But generally obj.prop would turn into pointer offset.

Note: for local variable the pointer could be the stack frame and the offset the offset of obj inside the stack frame the offset of prop inside Obj.

  • Related