Type Conversion

Type Conversion

Type Conversion, also known as typecasting, is a fundamental concept in C++ programming that involves converting one data type into another.

Type Conversions can be broadly categorized into two types: Implicit conversion and Explicit conversion

1️⃣ Implicit Conversion (coercion):

Implicit conversion, also known as automatic conversion, occurs when the compiler automatically converts one data type to another without any explicit instruction from the programmer. This conversion is performed to avoid data loss and to promote compatibility between different data types.

Example:

int intValue = 10;
float floatValue = intValue;  // Implicit conversion from int to float

In this example, the integer value intValue is implicitly converted to a floating-point number floatValue during the assignment.

2️⃣ Explicit Conversion:

Explicit conversion, also called type casting, is performed by the programmer using casting operators. There are two types of explicit conversion: C-style casting and functional casting.

C-Style Casting:

In standard C programming, casts are done vis the () operator, with the name of the type to convert the value placed inside the parentheses.

float floatValue = 10.5;
int intValue = (int) floatValue;  // C-style casting

While C-style casting is concise, it can lead to potential issues if used improperly. It can perform dangerous conversions and may not be easily recognized in the code.

Functional Casting (Since C++11):

float floatValue = 10.5;
int intValue = static_cast<int>(floatValue);  // Functional casting

C++ Casting Operators:

C++ introduces four casting operators for more clarity and type safety:

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast
float floatValue = 10.5;
int intValue = static_cast<int>(floatValue); // C++ static_cast from float to int

Using static_cast is generally preferred as it performs checks at compile-time and is more specific about the intended conversion.

static_cast

C++ introduces a casting operator called static_cast, which can be used to convert a value of one type to a value of another type.

#include <iostream>

int main()
{
    char c { 'a' };
    std::cout << c << ' ' << static_cast<int>(c) << '\n'; // prints a 97

    return 0;
}