Re: Limitations of initialization list

From: Chris Theis (Christian.Theis_at_nospam.cern.ch)
Date: 08/31/04


Date: Tue, 31 Aug 2004 17:51:00 +0200


"Marcin Kalicinski" <kalita@poczta.onet.pl> schrieb im Newsbeitrag
news:ch1vd8$fmn$1@korweta.task.gda.pl...
> Hi,
>
> Constructor of derived class needs to do some complex things before it
calls
> base class constructor. There is an ugly solution:
>
> bool ComplexThingToDo()
> {
> // ...
> return false; // dummy
> }
>
> class Derived: public Base
> {
> bool dummy;
> public:
> Derived(): dummy(ComplexThingToDo()), Base() { }
> };
>
> But I'm afraid that sequence of initializers in initialization list does
not
> enforce the actual sequence of execution. So this ugly solution will not
> work. Is there another way? Perhaps it is an example of bad design, doing
> some complex things before calling base class constructor?
>
> Best regards,
> Marcin
>

Naturally objects are constructed top to bottom in the inheritance tree.
However, you can enforce a specific order of executed base class ctors by
using multiple and virtual inheritance (see FAQ 25.14). This is a way to
solve your problem but still I have the itching feeling that you might have
a flaw in the design. Why can't the complex things be done by the base class
ctor? If they cannot but it is a problem if they are not yet done when the
base class ctor is executed then you might have a dependency of a base class
to a derived class and this is certainly a flaw. I don't suggest that this
is the case for you but you might consider rethinking your design.

Cheers
Chris



Relevant Pages

  • Re: Trouble with non-default constructors
    ... >> invoking a base class constructor. ... > to a base class or an embedded class. ... point is your suggested constructor signatures made no sense whatsoever. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Limitations of initialization list
    ... > Constructor of derived class needs to do some complex things before it calls ... > enforce the actual sequence of execution. ... Not if you can't change the base class. ... > some complex things before calling base class constructor? ...
    (comp.lang.cpp)
  • Re: add to a base constructor, not replace
    ... |>Is there a convenient way to add something to a base class constructor ... |> class RTError: public runtime_error ... would use ones own exception objects( ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Class hierarchy
    ... parameters and then invoke the base class constructor that ... Any code that has been written with the Quadrilateral base class might ... break if, say, a Square object is passed to it. ...
    (comp.lang.cpp)
  • Re: Class hierarchy
    ... > Any code that has been written with the Quadrilateral base class might ... > break if, say, a Square object is passed to it. ...
    (comp.lang.cpp)