Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion by constructors

Class X -> converted to Y by two ways 1) constructors, and 2) by conversion functions.
I understood the single argument constructor is used for conversion.

In the specification:

An implicitly-declared copy constructor is not an explicit constructor; it may be called for implicit type conversion.

Question:

So, that means not only single argument constructor is used for the conversion, but also copy constructor?. If so, which scenario it is used?. any snippet of sample code?

Kindly bear with me if the question is very basis.

like image 370
Whoami Avatar asked Jul 20 '12 14:07

Whoami


People also ask

What is C++ conversion operator?

Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.


2 Answers

Copy constructor is not an explicit constructor, so it will be used wherever possible. Copy constructor will "convert" only from the same type, so it is not a conversion in the full sense. However, for the sake of generality it is handy to call it one.

Read this paper: http://www.keithschwarz.com/cs106l/winter20072008/handouts/180_Conversion_Constructors.pdf if you want more details on conversion constructors.

like image 114
Sergey K. Avatar answered Sep 30 '22 10:09

Sergey K.


It basically means that you can do:

struct A {};
A a;
A b = a;

If the copy constructor was marked explicit that would fail to compile. You can test it by adding: explicit A( A const & ) {} to the struct and recompiling the program.

like image 29
David Rodríguez - dribeas Avatar answered Sep 30 '22 09:09

David Rodríguez - dribeas