Search code examples
c++oopcopy-constructorderivedinherited

Base class on the initialisation list of a derived class' copy constructor (C++)


Let the example be:

class Base {
  Base (const Base & copyFrom) { globalRegister (* this); }
}

class Derived {
  Derived (const Derived & copyFrom) : Base (copyFrom) {}
}

I've read suggestions to include the Base's copy constructor on the initialisation list of Derived in order to copy over the Base's properties (as in the example).

However, I have the Base's copy constructor passing itself (* this) to other object (to be registered with that object). Would that be a case where I actually must use (implicitly or explicitly) Base's (default) constructor on the initialisation list of Derived's copy constructor, and call the Base's copy constructor only in the body of Derived's copy constructor, when there is actually an object that can be attached by Base's copy constructor? Else - is (* this) a valid object?


Solution

  • Would that be a case where I actually must use (implicitly or explicitly) Base's (default) constructor on the initialisation list of Derived's copy constructor, and call the Base's copy constructor only in the body of Derived's copy constructor, when there is actually an object that can be attached by Base's copy constructor?

    Why on earth would you want to do that?
    (Oh, and you can not call a base class' copy constructor from a derived class' constructor's body. Only from its initialization list.)

    Else - is (* this) a valid object?

    The moment the base's initialization list has completed, all of base's members (and base classes) are fully constructed. The class itself, however, is only fully constructed when its constructor has finished.
    More importantly, the derived class' constructor hasn't even started yet, so the object is not a derived class' object yet.

    So whatever that registering function does, it has to take into account that the object's dynamic type is base and that its constructor hasn't finished yet. (To be safe, all it can do is to store the object's address somewhere.)