When the compiler sees this code:
SomeClass foo;
int x = foo.bar;
What is the process it goes about in retrieving the value of bar? I.e. does it look at some data structure representing the class definition? If so is this data structure generated at compile time or runtime?
The process starts when the compiler sees the definition for
SomeClass. Based on that definition, it builds an internal structure that contains the types of the fields inSomeClass, and the locations of the code for the methods ofSomeClass.When you write
SomeClass foo;the compiler finds the code that corresponds to the constructor forSomeClass, and creates machine instructions to call that code. On the next line you writeint x = foo.bar. Here the compiler writes machine instructions to allocate stack space for anint, and then looks at its data structure forSomeClass. That data structure will tell it the offset in bytes ofbarfrom the beginning of thefooobject. The compiler then writes machine code to copy the bytes corresponding tobarinto the memory forx. All of this machine code gets written into your executable.Generally, the data structures representing
SomeClassand other definitions are thrown away once compilation is done. What you have left is just a set of machine instructions. Those instructions are executed when you actually run your program, so that the constructor forSomeClassand the code to copyfoo.barintoxare executed by the CPU without any explicit knowledge of the structure of your objects.This is the general case. There are special cases for when you run your code under a debugger and for optimization, but this is generally what happens.