C++ explicit conversion and implicit conversion

Go To StackoverFlow.com

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.

2012-04-04 01:56
by XiaJun
possible duplicate of Is there a difference in C++ between copy initialization and direct initialization? (Answers to this question directly address the explicit vs implicit conversion question - Ben Voigt 2012-04-04 01:59
Sorry,I did not see these similar questions.OK,Thanks a lot~ - XiaJun 2012-04-04 02:08


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.

2012-04-04 02:42
by David Rodríguez - dribeas


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
2012-04-04 02:14
by jhenderson2099
Y y(x) is direct-initialization, and it will convert the types even if the constructor is marked explicit, as it performs an explicit conversion - David Rodríguez - dribeas 2012-04-04 02:43