Consider this:
class Foo {
private:
Bar x;
public:
Foo(int a) { // no initialization here since constructor is dependent on a following if-block
if (a==0) x=Bar(12,'a', 34); // some (int, char, int) constructor of Bar
else x=Bar(13); // (int) constructor of Bar
}
}
What this is supposed to do, is check the value of parameter a, and initialize Bar x with a certain constructor and certain parameters depending on a's value. The problem is however, that this is of course read by the compiler as
Foo(int a): Bar() { // !
if (a==0) x=Bar(12,'a', 34); // some Bar(int, char, int) constructor of Bar
else x=Bar(13); // Bar(int) constructor of Bar
}
The compiler adds Bar() to the initialization list, since I ommited it. It's now doubly initialized, once with its () constructor and once in the function body. But what if initializing Bar (even with its default constructor) is very costly (regarding performance) and I can't or don't want this double-initialization ?
How can I NOT initialize Bar x, until IN the actual constructor body? And if it's not possible, how would I best work around this problem?
Adding to this: Why was C++ designed in this way? Why does it force initialization of members before the actual constructor body?
I think you are asking the wrong question, instead of trying to inhibit initialization, you should just do it, i.e. spell your ctor as:
This will not cause any copies or moves (see here), and is as idiomatic as it gets.