Justin wrote:
Hello, first time posting.
If I have a base class and a derived class, is there only one way to
call the base constructor?
No. Constructors can be overloaded. The base can have many possible
constructors for you to call. If you don't specify one, then the
default one is used.
If there isn't a default one, and your constructor doesn't call it from
its initializer list, then you have an error.
i.e. Is this the only way I can call the base constructor (presuming
the base constructor took an int):
Derived::Derive d(int a) : Base(a)
{ ... }
This is the only way you can call /that/ base class constructor, yes.
I know the base class must be constructed before the derived class
is..so I guess my question is, is there any way that I can run some
code in the derived constructor before calling the base constructor?
No. You can only call base constructors in the base and member
initializer list.
Moreover, the order of appearance of expressions in that list isn't
necessarily the order in which they are evaluated. Be careful! The list
is a specification of what component gets what initialization. It is
not a sequential program.
If you call a constructor in an ordinary statement body, what happens
is that it returns a temporary object. A constructor is not invoked on
the ``this'' object.
By the time you run the constructor body, the base class parts are
already constructed. You can adjust the base class object by assigning
to its members, or calling additional routines in the base class
(two-step initialization) .
There is also a way to call a constuctor on some given piece of memory.
This is done by the so called ``placement new'' operator.
There is a trick you can do to re-initialize a base class differently.
You do a in-place destructor call to wipe out the base, and then a
placement new over it.
I would put this in the category of "black art", and would never do it
over anything other than bases which are POD's (plain old datatypes).
I'm pretty sure the behavior is undefined, since basically we are
destroying an object midway through a construction, re-constructing
that destroyed part of it and then depending on the remainder of the
construction going fine to build the derived parts on top of the
reconstructed bases.
:)