C++ Type Conversion

C++ allows us to convert data of one type to another. This is known as type conversion.

There are two types of type conversion in C++.

  1. Implicit Conversion
  2. Explicit Conversion (also known as Type Casting)

Implicit Type Conversion

The type conversion that is done automatically done by the compiler is known as implicit type conversion. This type of conversion is also known as automatic conversion.

Let us look into the small example which will give us a clear picture of implicit type conversion.

Output:

we have assigned int data to a double variable.

C++ Explicit Conversion

When the user manually changes data from one type to another, this is known as explicit conversion. Also known as typecasting.

There are three major ways in which we can use explicit conversion in C++. They are:

  1. C-style typecasting (also known as cast notation)
  2. Function notation (also known as old C++ style type casting)
  3. Type conversion operators

1. C-style Type Casting

As the name suggests, this type of casting is favored by the C programming language.  Also known as cast notation.

The syntax for this style is:

For example:

2. Function-style Casting

We can also use function like notation to cast data from one type to another.

The syntax for this style is:

For example:

3. Type Conversion Operators

Besides these two type castings, C++ also has four operators for type conversion. They are known as type conversion operators. They are:

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast

 

Brief description about each type:

• const_cast<type> (expr):

The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed.

• dynamic_cast<type> (expr):

The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object.

• reinterpret_cast<type> (expr):

The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa.

• static_cast<type> (expr): 

The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer.

 

Recommended Tutorials: