So in C++, you can have a reference (auto-resolved pointer) as a member of your class, if you initialize that member in the constructor with a like reference. That way you can have several objects that refer to the same thing, with no null pointer problems.

Then you try to inherit from that class with a class that includes an object of that type, not a reference. Easy, just pass a reference to the object to the base class constructor. That way you can have objects like the first, but they all refer to their own thing, with no code duplication.

Except it won't initialize the object until B's constructor is complete.

B::B(A& thingy): myreference(thingy) {
// boy I hope thingy isn't uninitialized data!
performSurgery(thingy.foo);
}
To solve this, you can't. There's no way to do it, and no one can ever write a program in C++ that does.

#C++ #programming #FuckEverything #opinions #ProveMeWrong
You can just move the uninitialized-myreference-using code into an init() function, and provide a second constructor with a dummy bool argument that doesn't call init. Then the derived class can invoke the dummy constructor, and call init explicitly. Still cludgy af.

Also there's a compiler warning that the object won't be initialized. (-Wreorder)
@cy Why would you want to do that ?
So that I can have several objects that refer to the same thing, with no null pointer problems.
@cy Using shared pointers is not an option ? I mean, it seems tricky but if it works for you that's great.
References are shared, and pointers. They just "can't" be null, so they can be used as a direct substitute for the object they refer to. Pretty sure std::shared_ptr is only for when you can't be sure when your object is going to go out of scope, so you need reference counting.

@cy Here your references won't be null, but you will need to ensure that the referenced value outlive all the objects that are referencing it. This is very tricky. From my experience, storing references as class members is not a good idea.

Edit: typos

The class is instanced by another class, which has the object. No chance any of the former will outlive the latter. It's really not hard to do. Reference counting, in my opinion, indicates a fundamental problem with the program's structure. There are exceptions, generally relating to things tied to user input or other external unpredictable influences on the code.