Implicit VS Explicit Conversion

Implicit VS Explicit Conversion

one uses a Y's constructor and one uses the assignment operator though.

Nope. In the second case it's not an assignment, it's an initialization, the assignment operator (operator=) is never called; instead, a non-explicit one-parameter constructor (that accepts the type X as a parameter) is called.

The difference between initialization and assignment is important: in the first case, a new object is being created, and it starts its life with the value that it is being initialized with (hence why a constructor is called), while assignment happens when an object is assigned (~copied) to an object that already exists and already is in a definite state.

Anyway, the two forms of initialization that you wrote differ in the fact that in the first case you are explicitly calling a constructor, and thus any constructor is acceptable; in the second case, you're calling a constructor implicitly, since you're not using the "classical" constructor syntax, but the initialization syntax.

In this case, only one-parameter constructors not marked with explicit are acceptable. Such constructors are called by some people "converting" constructors, because they are involved in implicit conversions.

As specified in this other answer, any constructor not marked as explicit can take part in an implicit conversion for e.g. converting an object passed to a function to the type expected by such function. Actually, you may say that it's what happens in your second example: you want to initialize (=create with a value copied from elsewhere) y with x, but x first has to be converted to type Y, which is done with the implicit constructor.

This kind of implicit conversion is often desirable: think for example to a string class that has a converting (i.e. non-explicit) constructor from a const char *: any function that receives a string parameter can also be called with a "normal" C-string: because of the converting constructor the caller will use C-strings, the callee will receive its string object.

Still, in some cases one-parameters constructors may not be appropriate for conversion: usually this happens when their only parameter is not conceptually "converted" to the type of the object being created, but it is just a parameter for the construction; think for example about a file stream object: probably it will have a constructor that accepts the name of the file to open, but it makes no sense to say that such string is "converted" to a stream that works on that file.

You can also find some more complex scenarios where these implicit conversions can completely mess-up the behavior that the programmer expects from overload resolution; examples of this can be found in the answers below the one I linked above.

More simply, it can also happen that some constructors may be very heavyweight, so the class designer may want to make sure that they are invoked explicitly. In these cases, the constructor is marked as explicit, so it can be used only when called "explicitly as a constructor" and doesn't take part in implicit conversions.

What is the difference between explicit and implicit type casts?

This is a little tricky because the "cast" syntax in C# actually does a range of different things (cast, primitive convert, bespoke convert, etc)

In an implicit cast, there is an obvious reference-preserving conversion between the two:

List<int> l = new List<int>();
IList<int> il = l;

The compiler can prove that this is safe just from static analysis (List<int> is always an IList<int>)

With an explicit cast, either you are telling the compiler that you know more than it does - "please believe me, but check anyway":

List<int> l = new List<int>();
IList<int> il = l;
List<int> l2 = (List<int>)il;

Although this cast is possible, the compiler won't accept that all IList<int>s are actually List<int> - so we must tell it to let it by.


In an implicit primitive conversion (providedby the language spec), it is generally assumed that there is a safe, non-risky, non-lossy (caveat: see Jon's comment) conversion:

int i = 1;
float f = i;

With an explicit primitive conversion, it is likely that the conversion could lose data, or is non-obvious:

float f = 1;
int i = (int)f;

With bespoke operators, all bets are off, and you'd have to look at the documentation. It could be a reference-cast, or it could be anything. It may follow similar rules to primitive conversions (example: decimal), or it could do anything randomly:

XNamespace ns = "http://abc/def"; // implicit
XAttribute attrib = GetAttrib();
int i = (int)attrib; // explicit (extracts text from attrib value and
// parses to an int)

Both of these run custom code that is context-specific.

Difference between implicit conversion and explicit conversion

An explicit conversion is where you use some syntax to tell the program to do a conversion. For example (in Java):

int i = 999999999;
byte b = (byte) i; // The type cast causes an explicit conversion
b = i; // Compilation error!! No implicit conversion here.

An implicit conversion is where the conversion happens without any syntax. For example (in Java):

int i = 999999999;
float f = i; // An implicit conversion is performed here

It should be noted that (in Java) conversions involving primitive types generally involve some change of representation, and that may result in loss of precision or loss of information. By contrast, conversions that involve reference types (only) don't change the fundamental representation.


Is the difference different in Java and C++?

I don't imagine so. Obviously the conversions available will be different, but the distinction between "implicit" and "explicit" will be the same. (Note: I'm not an expert on the C++ language ... but these words have a natural meaning in English and I can't imagine the C++ specifications use them in a contradictory sense.)

Difference between Implicit Conversion and Explicit Conversion in SQL Server

An explicit conversion occurs when you use the CONVERT or CAST keywords explicitly in your query.

An implicit conversion arises when you have differing datatypes in an expression and SQL Server casts them automatically according to the rules of datatype precedence.

For example nvarchar has higher precedence than varchar

CREATE TABLE Demo
(
X varchar(50) PRIMARY KEY
)

/*Explicit*/
SELECT *
FROM Demo
WHERE CAST(X AS NVARCHAR(50)) = N'Foo'

/*Implicit*/
SELECT *
FROM Demo
WHERE X = N'Foo' /*<-- The N prefix means nvarchar*/

The second execution plan shows a predicate of

CONVERT_IMPLICIT(nvarchar(50),[D].[dbo].[Demo].[X],0)=[@1]

Both the explicit and implicit conversions prevent an index seek in this case.

Implicit Casting vs Explicit Casting

Although short and char are both 16 bit (2-byte) variables their ranges differ.

Char is an unsigned variable.

Short is a signed variable.

The range of the a char type is from 0 up to 65535).

The range of a short is from (−32,768 up to 32,767).

Because of this difference java forces you to cast explicitly because a char that has value over 32,767 that is casted to a short can lead to an invalid conversion. The same goes for a negative short cast to a char.

This is also the reason you cast an int to long (since the value of an int will always fit in a long. But you have to explicitly cast a long to an int (telling the compiler that you are willing to accept the risk of dataloss / corruption)

Performance implicit -vs- explicit conversion in a SQL Stored Procedure?

I don't think performance should be your concern here: accuracy is the key.

If you allow an implicit conversion you cannot guarantee the scale and precision of the data type chosen by the optimizer.

If you explicitly declare the type then you are able to obtain a deterministic result.

If you really want to pick on performance then I imagine the explicit will be faster as the implicit will have to scan a sample of rows first in order to assume what type it should cast to.

Update: Imagine you have an implicit conversion on a value used in a comparison: if the implicit conversion data type does not match that of the comparative column you will incur a further performance problem.

Convert float to int implicit vs explicit (cast) discrepancy

To analyse this, the first job is to rewrite a += b as a = a + b.

i + (int)f will be computed in integer arithmetic due to the explicit cast.

But i + f will be computed in floating point arithmetic due to type promotion.

So the expressions have different types. Due to the way floating point works, the result, when converted back to an int could differ.

The moral of the story is to not use += for mixed types, and to not ignore helpful compiler warnings.

Explicit and implicit conversion

§6.4 Selection statements [stmt.select]


  1. The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch;

§4 Standard conversions [conv]

Certain language constructs require that an expression be converted to
a Boolean value. An expression e appearing in such a context is said
to be contextually converted to bool and is well-formed if and only
if the declaration bool t(e); is well-formed, for some invented
temporary variable t (8.5).

So the expression of the condition in if must be contextually convertible to bool, which means that explicit conversions are allowed.

This is mode most likely done because the condition of if can only evaluate to a boolean value, so by saying if(cond) you are explicitly stating you want cond to be evaluated to a boolean value.



Related Topics



Leave a reply



Submit