Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy constructor with default arguments

As far as I know, the copy constructor must be of the form T(const T&) or T(T&). What if I wanted to add default arguments to the signature?

T(const T&, double f = 1.0);

Would that be standards compliant?

like image 471
fredoverflow Avatar asked May 07 '10 09:05

fredoverflow


People also ask

Can we use default arguments with constructor?

Like all functions, a constructor can have default arguments. They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor.

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.

Is there a default copy constructor?

There is no such thing as a default copy constructor. There are default constructors and copy constructors and they are different things.

What is constructor with default argument?

Constructors with Default Arguments in C++ Default arguments of the constructor are those which are provided in the constructor declaration. If the values are not provided when calling the constructor the constructor uses the default arguments automatically.


2 Answers

Yes.

§[class.copy]/2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.

like image 183
kennytm Avatar answered Oct 11 '22 07:10

kennytm


You can just create two different constructors:

T(const T&)
T(const T&,double)

However, what you have is permitted as a copy constructor.

On a side note, I have discovered that it is generally not a good idea to use default parameters in C++, and it is instead much better to use overloads, where the ones with fewer parameters invoke the ones with more parameters, using default values (of course that isn't possible with constructors in ISO C++ 2003, but delegating constructors are permitted in ISO C++ 201x). The reason for this is that default values give your functions different actual signatures than their apparent behavior, making it somewhat difficult/painful when taking the pointers to the functions. By providing overloads, function pointers of each possible invocation type can be taken without requiring any sort of "binding" mechanism to make it work.

like image 41
Michael Aaron Safyan Avatar answered Oct 11 '22 08:10

Michael Aaron Safyan