Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the explicit keyword needed with a constructor taking more than one parameter?

Tags:

c++

c++03

This question pertains to the preceding standard of C++11 (C++03). explicit prevents implicit conversions from one type to another. For example:

struct Foo
{
    explicit Foo(int);
};

Foo f = 5; // will not compile
Foo b = Foo(5); // works

If we have a constructor that takes two or more parameters, what will explicit prevent? I understand that in C++11 you have braced initialization, so it will prevent constructions such as:

struct Foo
{
    explicit Foo(int, int);
};

Foo f = {4, 2}; // error!

But in C++03 we don't have braced initialization, so what kind of construction is the explicit keyword preventing here?

like image 628
template boy Avatar asked Mar 19 '15 13:03

template boy


2 Answers

It might be interesting if someone change the signature of your method with a default parameter :

struct Foo
{
    explicit Foo(int, int = 0);
};

With the explicit keyword, you idiomatically say that you do not ever want a constructor to do implicit conversion.

like image 86
neuro Avatar answered Oct 24 '22 05:10

neuro


If we have a constructor that takes two or more parameters, what will explicit prevent?

Nothing.

like image 43
Lightness Races in Orbit Avatar answered Oct 24 '22 05:10

Lightness Races in Orbit