c++ - How does the compiler distinguish nested objects if they have the same address? -


in following example (try out here)

#include <iostream> using namespace std;  struct {     struct b {         int b1;     };     b a1;     int a2; }; int main() {     test;     test.a1.b1 = 5;     test.a2 = 6;      std::cout<<&test<<" "<<&(test.a1);     // code goes here     return 0; } 

both struct , nestd struct have same memory location. makes sense, since first element stored in memory part of nested struct.

proof: 0x7ffd895f86e0 0x7ffd895f86e0

my question is: how compiler know types stored @ location , there overhead tracking such information @ runtime expected?

how this:

struct {     int x;     struct b {         int b1;     };     b a1;     int a2; }; 

do have same address? no. not because they're different, because "struct" has no binary meaning (before lashing this, keep reading). when program compiled, matters variables inside structs. programming language has superficial thing called "struct" make things easy you. it's not real, unless requires handled 1 thing (such copying it), , binary code generated (for run-time) represent elements copied whole, not "struct", per se.

when instantiate a there, how looks in memory:

int x - int b1 - int a2 

it's blocks in memory ints. it's not structs.

you can verify using pointers. in code:

*(int*)(&test) //is b1 *((int*)(&test)+1) //is a2 

so see there's 2 ints in memory matter.

ps: notice assumes we're not dealing polymorphism, adds more memory blocks represent vtable. that's story day.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -