0

Given the types

struct A
{ 
    A(int);
};

struct B : A 
{ 
    int x;
    B();
};

is there any impactful reason to prefer the call to the constructor of A before the initialization of x? By impactful I mean effect on the behavior on the program rather than "it's good/common practice to do so".

B::B() : A(10), x(5) { }

// can this difference affect the programs behavior somehow?

B::B() : x(5), A(10) { }

The standard doesn't seem to forbid or reason about this, so I assume reordering the mem-initializer-list is well defined.

Timo
  • 9,269
  • 2
  • 28
  • 58
  • 2
    `A`'s initialization happens first no matter what. Warnings about this are just so you don't accidentally rely on the order of the members in the list. For example, `x(5), A(x)` won't work because `x` will be uninitialized when `A(x)` happens. – François Andrieux Jan 23 '20 at 20:47
  • 1
    Does this answer your question? [Constructor initialization-list evaluation order](https://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order) – Enlico Jan 23 '20 at 20:48
  • @FrançoisAndrieux Don't you mean that the base class will be initialized first? Then, subsequently, member variables will be initialized in declaration order. – Jesper Juhl Jan 23 '20 at 20:58
  • @JesperJuhl I think he was trying to point out that such an initialization would be ill-formed. – Timo Jan 23 '20 at 21:01
  • @JesperJuhl That's what I meant by *"A's initialization happens first no matter what."* `A` is the base class, it will be initialized first. – François Andrieux Jan 23 '20 at 21:07
  • @FrançoisAndrieux I'm an idiot. I was reading your comment too quickly on my phone and read `A` as `x`. My apologies. – Jesper Juhl Jan 23 '20 at 21:10

0 Answers0