Reputation:
I know that a copy constructor is a constructor that makes a new object as a copy of an existing object, but, is every constructor that takes another object as an argument called a copy constructor?
Example: If I have to classes X
and Y
is X(const Y& y)
a copy constructor?
If not is there a name for such constructor?
Upvotes: 1
Views: 108
Reputation: 310980
No this
X(const Y& y);
is not a copy constructor. The copy constructor shall define the first parameter having the same type (with/without qualifiers) as the created object
According to the C++ Standard
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
Constructor
X(const Y& y);
is a conversion constructor that converts an object of type Y to an object of type X.
Upvotes: 2
Reputation: 320531
If X
and Y
are different types, then
X(const Y& y)
would be a conversion constructor.
Note that copy constructor is considered a special case of conversion constructor (for X==Y
).
Upvotes: 1
Reputation: 103515
No. A copy constructor is one which takes a single instance of the same class as it a ctor for. Hence
X(const X& x)
is a copy constructor, as would be:
X(const X& x, int z = 0)
since it can be called with just the single x
object.
Constructors which take some other object are often called "converting constructors", but that name is as fixed as "copy constructor".
Upvotes: 5