Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy constructor parameters

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

like image 311
haris Avatar asked Jan 30 '12 15:01

haris


1 Answers

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.

like image 80
Alok Save Avatar answered Sep 26 '22 02:09

Alok Save