Home > Back-end >  Is Passing Reference From Child To Parent During Construction UB?
Is Passing Reference From Child To Parent During Construction UB?

Time:03-31

The following is a simplified version of some code.

struct Test {
    Test( int &id ) : id( id ) {}
    int &id;
};

struct B : Test {
    B() : Test( a ) {}
    int a;
};

Now, I'm aware that the parent, in this case Test would be created before the B object when a B object is created. Does that then mean that the a variable, being passed in to the Test constructor, does not yet have an address and is thus Undefined Behaviour? Or is this safe?

Just to clarify, the value of id is not used until after B is fully constructed.

CodePudding user response:

Yes your code is fine.

You can use memory addresses and reference to not yet initialized members in the constructor. What you cannot do is using the value before it has been initialized. This would be undefined behavior:

struct BROKEN {
    BROKEN( int* id ) : id(*id) {}
    int id;               // ^ -------- UB
};

struct B : BROKEN {
    B() : BROKEN( &a ) {}
    int a;
};

[...] being passed in to the Test constructor, does not yet have an address and is thus Undefined Behaviour

Consider what happens when an object is created. First memory is allocated, then the constructor is called. Hence "does not yet have an address" is not correct.

  • Related