Programming

C++ – Type Conversion and Ways of Typecasting

Type conversion refers to the local modification of type for variable or subexpression. Type conversions depend on the specified operator and the type of the operand or operators. Type conversions are performed in the following cases:

  • When a value of one type is assigned to a variable of a different type or an operator converts the type of its operand or operands before performing an operation
  • When a value of one type is explicitly cast to a different type
  • When a value is passed as an argument to a function or when a type is returned from a function

Suppose that integers are converted to floats when necessary, using a unary operator (float). For example, the integer 2 is converted to a float in the code for the expression 2*3.14

  • T1=(float)2
  • T2=t1*3.14

Types of Typecasting

There are two ways of achieving Typecasting.

These are:

Implicit Conversion

Implicit type conversion is not done by any conversions or operators. In other words, the value that gets automatically converted to the specific type to which it is assigned is known as implicit type conversion. Example

  • short a=2000;
  • int b;
  • b=a;

Here, the value of ‘a’ is promoted from short to int without the need of any explicit operator. This is known as a standard conversion.

Standard conversions affect fundamental data types, and allow the conversions between numerical types (short to int, int to float, double to int…), to or from bool, and some pointer conversions.

Read: Introduction to OOP and It’s Characteristics

Explicit Conversion

Explicit conversion can be done using the type cast operator. In other words, the value that gets converted to the specific type by using the type cast operator is known as explicit type conversion.

C++ style casting: new_type(expression) dynamic_cast <new_type> (expression) reinterpret_cast <new_type> (expression) static_cast <new_type> (expression) const_cast <new_type> (expression)

User Defined Conversion

User-defined conversions allow you to specify object conversions with constructors or with conversion functions. User-defined conversions are implicitly used in addition to standard conversions for conversion of initializes, functions arguments, function return values, expression operands, and expressions controlling the iteration, selection statements, and explicit type conversions.

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.