Marcus Kwok wrote:
> Oliver S <> wrote:
> > I got a class, a VCL form actually. I have two const member that I am
> > initializing (in the order they were declared). My question is, do I put
> > them before calling inherited constructor or after? In other works, should
> > it look like this or like that?
> >
> > __fastcall TfMJTuner::TfMJTuner(TComponent* Owner)
> > : OriginalWidth(Width), OriginalHeight(Height), TForm(Owner)
> >
> > or
> >
> > __fastcall TfMJTuner::TfMJTuner(TComponent* Owner)
> > : TForm(Owner), OriginalWidth(Width), OriginalHeight(Height)
> >
> >
> > The damn thing works either way, I wonder which way is the proper way?
>
> My reasoning would be to put the base class constructor first, since
> logically you want to fully construct the base class object before
> initializing the derived part of the class.
This is done automatically by the compiler. The order in the
initialization list does not matter (except for a "logical" order to
help you and your coworkers). In fact, this:
class A
{
public:
A()
: b(5), a(b)
{
}
private:
int a, b; // <-- note the order!
};
is trouble. Since 'b' was declared after 'a', it will be initialized
after. That means 'a' will use 'b' before it is initialized (undefined
behavior). See
http://gotw.ca/gotw/080.htm for more informations on the
order of initialization in a class hierarchy.
Jonathan