Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a copy constructor have more than one parameter?

$12.8/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 (8.3.6).106)'

So far, I have not come across any example of a situation where there is a need to declare a copy constructor with additional default parameters.

Would like to know any real time use of such a copy constructor which take more than one parameter.

like image 496
Chubsdad Avatar asked Sep 06 '10 03:09

Chubsdad


People also ask

Can a copy constructor have multiple arguments?

A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them.

How many parameters does a copy constructor have?

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.

Can a constructor have more than one parameter?

The technique of having two (or more) constructors in a class is known as constructor overloading. A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.

Why does a copy constructor have constant argument?

When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.


2 Answers

The old std::basic_string does have one too:

basic_string(const basic_string& s, 
         size_type pos = 0, size_type n = npos)
like image 95
dirkgently Avatar answered Oct 02 '22 17:10

dirkgently


The BDE allocator [PDF Link] used this quirk. For example their array allocator looked like this:

template <typename T>
class bde::Array {
public:
    Array(bde::Allocator *allocator = 0);
    Array(const Array &rhs, bde::Allocator *allocator = 0);
};
like image 25
Evan Teran Avatar answered Oct 02 '22 16:10

Evan Teran