8

The question came up in a discussion at StackOverflow.

Is there a clean distinction between the two concepts cast and convert (concerning the type of an object), or are these two words describing exactly the same? How about languages other than C++, Python and Java? EDIT: What if the types in question are primitive types, like int to float?

krlmlr
  • 793

3 Answers3

5

Theoretically speaking, the two concepts are vastly different:

Type Casting refers to exchanging one type (roughly speaking, an object structure) for another while Type Conversion refers to translating of values (roughly speaking, contents of the object), so that they may be interpreted as belonging to a new type. Theoretically, they never mix.

That said, practically speaking, while you can have one without another, it's, almost always, a bad idea. It rarely makes sense to change your perception of an objects' structure, without also altering its contents. Practically, they're almost always the same

3

Different languages define the words "cast" and "convert" differently; I don't think the question is meaningful other than in reference to a particular language.

In C, for example, the term "cast" properly refers only to an explicit cast operator, consisting of a type name in parentheses preceding the expression to be converted. A "conversion" converts a value of one type to a value of another type; some conversions are implemented by re-interpreting the bits that make up the representation, but it's defined as a value-to-value conversion. (Yes, that's true even for pointer conversions; it's possible for different pointer types to have different representations.)

Note that there is no such thing as an "implicit cast" in C.

Some conversions are explicit, specified by a cast operator. Others are implicit, and are applied in certain cases when an expression of one type is used in a context that needs an expression of a different type. The conversion performed is exactly the same in either case.

For example:

double x = 1.23;
int y = (int)x;  /* A cast, or explicit conversion, setting y to 1 */
int z = x;       /* An implicit conversion, setting z to 1. */

C++ is similar; it has the same casts and conversions as C, and it adds a functional notation equivalent to a C-style cast expression, plus 4 more specific keywords: const_cast, dynamic_cast, reinterpret_cast, and static_cast.

Keith Thompson
  • 6,442
  • 2
  • 30
  • 36
1

While casting, you read the instance of one class as if it is the instance of another class. It could be appliccable for this pair of classes or not. No runtime work except checking. Often the possible incompatibility could be caught on compiling stage.

While converting, you recombine or recount fields of an instance of one class into an instance of another class. If there is a function for it, it could be applicable or not for this very instance. All the work is done during runtime. No error could be checked while compiling.

Gangnus
  • 2,817