Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit keyword on multi-arg constructor?

I recently came across some weird looking class that had three constructors:

class Class {     public:         explicit Class(int );          Class(AnotherClass );          explicit Class(YetAnotherClass, AnotherClass );      // ... } 

This doesn't really make sense to me - I thought the explicit keyword is to protect compiler chosen construction from a foreign type.

Is this allowed? If it it, what does it mean?

like image 265
LiraNuna Avatar asked Jul 13 '09 10:07

LiraNuna


People also ask

What is the explicit keyword?

The explicit keyword in C++ is used to mark constructors to not implicitly convert types. For example, if you have a class Foo − class Foo { public: Foo(int n); // allocates n bytes to the Foo object Foo(const char *p); // initialize object with char *p };

Can a copy constructor have multiple arguments?

A copy constructor has one parameter that is a reference to the type that is copied. It can have additional parameters, if these have default values.

What is argument in constructor?

It is used to prevent a specific constructor from being called implicitly when constructing an object. For example, without the explicit keyword, the following code is valid C++: Array a = 10; This will call the Array single-argument constructor with the integer argument of 10.


1 Answers

In C++11 multi-parameter constructors can be implicitly converted to with brace initialization.

However, before C++11 explicit only applied to single-argument constructors. For multiple-argument constructors, it was ignored and had no effect.

like image 116
Roger Lipscombe Avatar answered Sep 30 '22 03:09

Roger Lipscombe