Implicit constructor arguments

I always thought that an implicit constructor in C ++ could only be a constructor with one argument. For instance:

class Foo1
{
   Foo(int); // This could be an implicit constructor
};

But is the following code true:

class Foo2
{
    Foo2(int, int=0);  // Would compiler use this as an implicit constructor?
}

I can do it:

Foo1 obj;
...
obj = 5;

How about Foo2?

+5
source share
4 answers

First, any constructor can be tagged explicit. How many arguments it has does not matter.

From this point of view, you just need to understand what it means explicit. It just means that the only way the constructor can be called is when you explicitly specify the class name:

struct foo
{
    foo(int){}
    explicit foo(double){}
};

void bar(foo){}

bar(5); // okay, calls foo(int) to construct the foo
bar(3.14); // error, cannot call foo(double) because foo was not explicitly used
bar(foo(3.14)); // okay, calls foo(double) to construct the foo

The reason we do not highlight constructors with multiple arguments is due to its futility. Given:

struct baz
{
    baz(int, int, int);
};

, baz? ( baz(1, 2, 3).) †

explicit , . , , , , .


† ++ 11. ++ 11, , :

void qaz(baz) {}

qaz({1, 2, 3}); 

, , , .

+7

, , .

, ctor, , . , ctor explicit. ctor, , , , .

+2

EXplicit Implicit . . : , () .

: , Foo2(int, int=0) - , , obj = 5, int.

: , .

+1

, , , , , .

, ( , ):

Foo1 obj; //this line will not compile as it takes one argument!
obj = 5;

, , , .

, ,

Foo1 obj(10); //OK now
obj = 5;

, .

Foo2? , Foo2:

Foo2 foo(10);
foo = 5;
+1

All Articles