Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading