5
votes

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.

4
The copy-constructor IS a single-argument constructor. But it doesn't change the type, so I don't know why anyone would call it a "conversion". - Ben Voigt
I'm pretty sure my wife will get upset if I "bare with" you. :-) - Jerry Coffin
haha, Jerry, Thanks for pointing out. :) - Whoami

4 Answers

3
votes

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.

2
votes

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.

1
votes

Implicitly-declared copy constructor cannot use for conversions, since it's copy-ctor, that has declared as T(const T&) or T(T&).

draft n3337 par 12.8 C++ standard.

8 The implicitly-declared copy constructor for a class X will have the form X::X(const X&) if — each direct or virtual base class B of X has a copy constructor whose first parameter is of type const B& or const volatile B&, and — for all the non-static data members of X that are of a class type M (or array thereof), each such class type has a copy constructor whose first parameter is of type const M& or const volatile M&.119 Otherwise, the implicitly-declared copy constructor will have the form X::X(X&)

Since copy c-tor is not explicit you can use such code

struct So
{
};

int main()
{
    So s = So();
}

If copy-ctor is explicit you could use only initizaliation like So s((So()));

1
votes

An implicit copy constructor is one that the compiler writes for you. It always has the form

T(const T&);

This means that any object which has a conversion operator to const T& can be implicitly copied, even if this isn't what you wanted. The most common way to trigger this is to make a copy to a base class from a derived class; this is called object slicing because the copy won't have the same type as the original and will probably lose some important properties or behavior.