ChrisMM
ChrisMM

Reputation: 10022

Is Passing Reference From Child To Parent During Construction UB?

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.

Upvotes: 6

Views: 130

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122486

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.

Upvotes: 9

Related Questions