9

In a copy constructor why do arguments need to have default values associated with them? What happens if there are no default values associated with them and more than one argument is provided in the constructor?

For example:

X(const X& copy_from_me, int = 10);

has a default value for the int, but this:

X(const X& copy_from_me, int);

does not. What happens in this second case?

http://en.wikipedia.org/wiki/Copy_constructor

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
haris
  • 2,003
  • 4
  • 25
  • 24

4 Answers4

11

A copy constructor always takes one parameter, reference to the type for which it belongs, there maybe other parameters but they must have default values.

An copy constructor is called as an copying function and the purpose of the copy constructor is to create an object of a type by using an object of the same type as basis for creation of the new type.

The Standard specify's that the copy constructor be of the type:

T(const &T obj);

This basically allows creation of temporary objects during calling functions by value or returning objects of the type by value.
This syntax facilitates creation of an new object as:

T obj1(obj2);      <--------- Direct Initialization
T obj1 = obj2;     <--------- Copy Initialization

If the additional arguments being passed to the copy constructor would not be mandated to have default values then the construction of objects using the above syntax would not be possible.
Hence the strict condition,
there maybe other parameters to a copy constructor but they must have default values.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
10

When a copy constructor is invoked, the only thing that's guaranteed to be available is a reference to an instance of the same class. If the copy constructor takes arguments beyond this required reference, those arguments must have default values.

Let's say we have a constructor with the following signature:

 X(const X&, int);

This cannot be used as a copy constructor because of the second argument. For example:

 X x1;
 X x2(x1);

How would the compiler use the above constructor for x2? It can't.

On the other hand, the following can be used as a copy constructor:

 X(const X&, int = 0);
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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. If they don't have default values, it just isn't a copy constructor.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
1

A copy constructor has to be callable with just an object of the type to be copied:

Thing t1;     // default constructor
Thing t2(t1); // copy constructor

If there are extra arguments without default values, then the constructor can't be called like that, so it isn't a copy constructor.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644