Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit constructor arguments

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

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

But is the following code right:

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

I can do this:

Foo1 obj;
...
obj = 5;

What about Foo2?

like image 483
Max Frai Avatar asked Feb 16 '12 02:02

Max Frai


1 Answers

First, any constructor can be marked explicit. How many arguments it has is irrelevant.

With that out of the way, you just now need to understand what explicit really means. It just means that the only way that 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 don't mark multiple-argument constructors explicit is because it's useless. Given:

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

How else can you call that constructor other than saying baz anyway? (As in baz(1, 2, 3).)†

In your example, explicit would be sensible because you could call that constructor with only one argument. What you actually do only depends on if you feel it should be implicitly convertible or not.


†This is disregarding C++11 initializer lists. In C++11, I think you could say:

void qaz(baz) {}

qaz({1, 2, 3}); 

And manage to get an implicit conversion to a multiple-argument constructor, but I don't know enough about initializer-lists to make a meaningful comment except as a footnote.

like image 134
GManNickG Avatar answered Sep 30 '22 21:09

GManNickG