C ++ compiler - resolving member name of a class

When the compiler sees this code:

SomeClass foo;
int x = foo.bar;

What is the process that it performs when retrieving the bar value? So he is looking at some data structure representing a class definition? If so, is the data structure generated at compile time or runtime?

+3
source share
5 answers

The process begins when the compiler sees the definition for SomeClass. Based on this definition, it creates an internal structure that contains the types of fields in SomeClass, and the location of the code for the methods SomeClass.

SomeClass foo;, , SomeClass, . int x = foo.bar. int, SomeClass. bar foo. , bar, x. .

, , SomeClass , . . , , SomeClass foo.bar x - .

. , , .

+2

foo. - (sizeof(SomeClass)), , , .

, `bar - ( , - ) .

:

struct SomeClass
{
    short s;
    float f;
    int bar;
    char *c;
}

// pseudo-code:
&SomeClass.bar == (&SomeClass) + sizeof(short) + sizeof(float);

x

+6

, , SomeClass. , , .

, ( ) . , , , - , , foo. , , - (, , , - ).

+4

, ( ), ,

class Foo
{
   int x, y, z;
   char bar[10];
   ... etc ...
}

, 4 * 3 + 10 . , , , , 4 y, 8 z.

, 4 , , y ..

+1

The compiler saves such class metadata only at compile time. Your first question, how it extracts the value of a bar, is actually quite complicated. You could think of it as calculating the offset of the bar from the foo object, and then read the memory at that location. However, depending on how x is actually used, it may do something completely different. In some situations, “x” may not appear at all in compiled code.

+1
source

Source: https://habr.com/ru/post/1722062/


All Articles