[ACCEPTED]-C++ Instance Initialization Syntax-initialization

Accepted answer
Score: 20
class Foo {
    Foo(explicit int);

    Foo& operator=(int);

That's invalid. The syntax is

class Foo {
    explicit Foo(int);

    Foo& operator=(int);

The difference 19 is that the conversion constructor cannot be used for implicit 18 conversions when you put explicit before it:

Foo f(10); // works
Foo f = 10; // doesn't work

The 17 above doesn't have anything to do with an 16 assignment operator you declared there. It 15 is not used since that is an initialization 14 (only constructors are used). The following 13 will use the assignment operator:

Foo f;
f = 10;

And will 12 use the default constructor of Foo (the 11 one taking no arguments).

Edit: The questioner 10 changed his question to the specific ways 9 of whether

Foo f = 1; // called "copy initialization" 
Foo f(1);  // called "direct initialization"

Are the same. The answer is that 8 they are equivalent to the following:

Foo f(Foo(1));
Foo f(1);

If 7 and only if the conversion constructor taking 6 the int is not declared with keyword explicit, otherwise 5 the first is a compiler error (see above). The 4 compiler is allowed to elide (optimize out) the 3 temporary passed to the copy constructor 2 of Foo in the first case if all semantic restrictions are still safisfied, and even if the copy constructor has side effects. That especially 1 includes a visible copy constructor.

Score: 9
Foo f = 42;

This statement will make a temporary object 3 for the value '42'.

Foo f(42);

This statement will 2 directly assign the value so one less function 1 call.

More Related questions