Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused between a copy constructor and a converting constructor

Since I have doubts about this question (for C++03) I am posting it here.I just read about conversion constructors and it states that

"To be a converting constructor, constructor must have single argument and be declared without keyword explicit."

Now my question is whether the copy constructor can be called a conversion constructor provided it is not explicitly declared ? Does it qualify to be one ? I believe it cant be called a conversion constructor because it only accepts the same type parameter ths resulting in no conversion. For Instance

foo a;
foo b;
a = 100; //a Conversion constructor would be called (i.e) foo(int a){...}
a = b ;  //Since both objects are same type and have been initialized the assignment operator will be called (if there is an overloaded version otherwise the default will be called)

Is my understanding correct ?

like image 277
Rajeshwar Avatar asked Aug 23 '13 14:08

Rajeshwar


People also ask

What is the difference between copy constructor and move constructor?

If any constructor is being called, it means a new object is being created in memory. So, the only difference between a copy constructor and a move constructor is whether the source object that is passed to the constructor will have its member fields copied or moved into the new object.

What is the difference between a copy constructor and copy assignment function?

The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space.

What is a converting constructor?

A conversion constructor is a single-parameter constructor that is declared without the function specifier explicit . The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor's class.


2 Answers

Quoting the Standard:

[class.conv.ctor]/3

A non-explicit copy-constructor (12.8) is a converting constructor. An implicitly-declared copy constructor is not an explicit constructor; it may be called for implicit type conversions.

So yes, a copy-ctor is a converting ctor.

Also note [conv]/1 which specifies and points out in a remark:

Note: a standard conversion sequence can be empty, i.e., it can consist of no conversions.

and in /3:

An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed

So the set of implicit conversions contain the empty conversions.

like image 174
dyp Avatar answered Sep 27 '22 21:09

dyp


Yes, a copy constructor is what it is -- a copy constructor. Which isn't a conversion constructor that converts from one type to a different type.

like image 32
Paul Evans Avatar answered Sep 27 '22 20:09

Paul Evans