C++ standard: why are some "orders" defined and some not?

140 views Asked by At
  1. Having a class, the initialization order of its members is strongly defined in constructor (maybe to allow dependencies between members, like in this question - but I think this is more a design problem, I can imagine circular dependencies).
  2. Having a function call, the order of parameters evaluation isn't defined, I think it's for C compatibility.
  3. And we have an error for the following "dreaded diamond" problem:

    struct A {virtual void Print() {}};
    struct B: virtual public A {virtual void Print() {}};
    struct C: virtual public A {virtual void Print() {}};
    struct D: public B, public C {};
    

    The compiler doesn't know which version to choose, the order being defined as ambiguous. Why simply not use a "left-to-right depth first resolution order" as defined in this question (with an unconvincing answer), namely to choose B over C?

So why these different approaches? Why there's a strict order for 1 and not for 3? Wasn't more simple to keep 1 undefined? Or 2 simply defined as left-to-rigth?

1

There are 1 answers

3
Vaughn Cato On

These are very different situations with various trade-offs. In each case you have to consider

  • How often do these situations occur?
  • How likely is an arbitrary choice to have unexpected consequences?
  • How easy is it to explicitly specify when a specific order is needed?
  • What performance penalties are caused by forcing a particular order?

The answers to these questions are quite different in each situation, so having different choices is natural.