Q:

Automatic determination of the constructor initialization list by the compiler?

I was asking myself (and couldn't find an answer) if the modern C++ compilers could check into the body of the constructors to see if they could infer the initialization list, instead of letting the developer specifying it?
As an example, consider the following code:
MyClass::MyClass (Obj o)
{
    _o = o;
}

Can the compiler automatically translate it into:
MyClass::MyClass (Obj o) : _o(o)
{}

Thanks

A:

This is not possible as it completely changes the semantics of the program in the general case. Some of the examples:
// Order of evaluation:
struct Foo {
   int a, b;
   Foo() : b(a) { a = 1; }    // differs from Foo() : a(1), b(a) {}
};

// Legality of the operation:
struct X { explicit X(int x); };
struct Foo {
    X x;
    Foo() { x = 5; }              // Ill formed, while Foo() : x(5) is well formed
};

// Different effects even if allowed
struct X {
   X(int)            { std::cout << "int\n";        }
   X()               { std::cout << "default\n";    }
   X& operator=(int) { std::cout << "assignment\n"; }
};
struct Foo {
   X x;
   Foo() { x = 5; }          // prints: default\nassignment\n
   // Where Foo() : x(5) {}  // prints: int\n
};

At the language level both operations are completely different and cannot be transformed. That being said, the optimizer might be able to produce the exact same code for both if they are truly equivalent.

