1

Look at the following two ways to create a new object of class Y:

(1)

X x;
Y y(x);//explicit conversion

(2)

X x;
Y y = x;//implicit conversion

The first way uses explicit conversion and another uses implicit conversion.But,I don't very understand how they work.What is their difference?Could someone interpret for me?The more detailed,the better.Thanks a lot.

XiaJun
  • 1,855
  • 4
  • 24
  • 41
  • [Existing questions about copy vs direct initialization](https://www.google.com/search?q=site%3Astackoverflow.com+copy+direct+initialization) – Ben Voigt Apr 04 '12 at 01:58
  • possible duplicate of [Is there a difference in C++ between copy initialization and direct initialization?](http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati) (Answers to this question directly address the explicit vs implicit conversion question) – Ben Voigt Apr 04 '12 at 01:59
  • Sorry,I did not see these similar questions.OK,Thanks a lot~~ – XiaJun Apr 04 '12 at 02:08

2 Answers2

1

The first is called direct-initialization while the second is called copy-initialization. Assuming that Y has a constructor that takes a X (or reference to it), direct-initiazliation will call that constructor directly and regardless of whether the constructor is marked as implicit. copy-initialization semantically is equivalent to:

Y y( implicit_conversion<Y>(x) );

That is, the argument is converted by means of an implicit conversion to the destination type and then the copy constructor is called to initialize the variable. In real life, the compiler will remove the copy and convert in place of the destination variable, but the compiler must check that there is an implicit conversion from X to Y, and the copy constructor is accessible.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

Actually, both are implicit conversions assuming that your class "Y" has a constructor like:

public:
  Y(X &x)

A class constructor with a single argument will perform the conversion for you.

To avoid implicit construction, use one of the following (one may be better for you based on your situation):

  • Don't declare a constructor with a single argument
  • Use the explicit keyword on the constructor declaration
  • Use an intermediate class (in other words only allow 'Y' to be initialized by 'Z', a class that never be assigned directly to 'Y')
  • Use a static member function to explicitly 'make' an instance of 'Y' using an 'X' (since the member function is not associated with an instance of the class
jhenderson2099
  • 956
  • 8
  • 17