Difference between implicit conversion and explicit conversion

73,010

Solution 1

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.)

Solution 2

You Mean Casting? Implicit mean you pass an instance of type, say B, that inherits from a type, say A as A.

For example:

Class A;
Class B extends A;

function f(A a) {...};

main() {
  B b = new B;
  f(b); // <-- b will be implicitly upcast to A.
}

There are actually other types of implicit castings - between primitives, using default constructors. You will have to be more specific with your question.

implicit with default constructor:

class A { 
  A (B b) { ... };
}

class B {};

main() {
  B b = new B();
  A a = b; // Implict conversion using the default constructor of A, C++ only.
}
Share:
73,010
saplingPro
Author by

saplingPro

I love to write code and love to be known as a programmer. I try very hard to be creative. I am a hard working man ! I don't know where i am heading and don't know where i will be :(

Updated on June 19, 2020

Comments

  • saplingPro
    saplingPro almost 4 years

    Possible Duplicate:
    Implicit VS Explicit Conversion

    What is the difference between "implicit conversion" and "explicit conversion"? Is the difference different in Java and C++?