Cast Expressions

The cast operator is used for explicit type conversions. It converts the value of the operand to a specified data type and performs the necessary conversions to the operand for the type.

For C, the operand must be scalar and the type must be either scalar or void. For C++ , the operand can have class type. If the operand has class type, it can be cast to any type for which the class has a user-defined conversion function.

The result of a cast is not an lvalue unless the cast is to a reference type. When you cast to a reference type, no user-defined conversions are performed and the result is an lvalue.

There are two types of casts that take one argument:


Both types of casts convert the argument a to the type X. In C++, they can invoke a constructor, if the target type is a class, or they can invoke a conversion function, if the source type is a class. They can be ambiguous if both conditions hold.

A function-style cast with no arguments, such as X(), creates a temporary object of type X. If X is a class with constructors, the default constructor X::X() is called.

A function-style cast with more than one argument , such as X(a,b), creates a temporary object of type X. This object must be a class with a constructor that takes two arguments of types compatible with the types of a and b. The constructor is called with a and b as arguments.



Conversion by Constructor
Conversion Functions
Type Specifiers
Resolving Ambiguous Statements in C++