0

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?

tweekz
  • 187
  • 1
  • 9
  • 2
    On the platforms I work on, yes, that's basically what happens. (There's additional hand-waving for inheritance or multiple inheritance.) But that's an implementation detail, and not required by the C++ standard. – Eljay Jul 15 '22 at 18:24

1 Answers1

1

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.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
  • Where are the offsets for the properties stored? – tweekz Jul 16 '22 at 09:24
  • Nowhere really. They are known at compile time and used to generate code. But unless you create a member pointer those offsets are compiler internals and not objects. – Goswin von Brederlow Jul 16 '22 at 10:47
  • OK, as you mentioned &Obj::prop I thought it was stored in the class object - as every instance has the same shape, it would work fine. – tweekz Jul 16 '22 at 11:06