How to create a member in the base class after the constructor of the subclass?

Hi,

Looking at std::enable_shared_from_this<T>, literature says that its method shared_from_this() cannot be called inside the constructor for the subclass (in the case T) because the data member used by that method is created AFTER the end of the constructor of the subclass T. And yet, I always thought that during construction, the base class was fully created before the subclass....

Was I wrong? If so, how can you accomplish the order of creation exemplified by the sample shared_from_this()?

Thanks,
Juan
I think you've misunderstood something you've read.

shared_from_this must be called from an object that is owned by a shared_ptr. There is no way to guarantee that an object is owned by a shared_ptr in its constructor.

Consider:

std::shared_ptr<A> a(new A);

The expression new A must be fully evaluated before before it is fed to the shared_ptr constructor, so it will not be owned by a shared_ptr in its constructor.
Last edited on
Thanks! Yes, I think the book was not clear on it, because that's what it said... but your explanation makes more sense indeed!!!

Topic archived. No new replies allowed.