In C++ Type casting is converting a value from one type to another.

there are two type of casting explicit and implicit.

Implicit Type Conversion

Implicit type conversion is performed automatically by the compiler whenever a value needs to be converted to a compatible type. It commonly occurs when:

  • Performing operations on values of different data types.
  • Passing arguments to functions expecting a different type.
  • Assigning a value of one type to a variable of another compatible type.
#include <iostream>
using namespace std;
 
int main() {
  
    int i = 10;
    char c = 'a';
 
    // c implicitly converted to int. ASCII
    // value of 'a' is 97
    i = i + c;
 
    // i is implicitly converted to float
    float f = i + 1.0;
 
    cout << "i = " << i << endl
         << "c = " << c << endl
         << "f = " << f;
 
    return 0;
}

Explicit Type Conversion

Explicit type conversion, also known as type casting, is performed manually by the programmer to convert a value from one type to another.

C++ provides dedicated cast operators that make conversions safer and more explicit.

Types of C++ Cast Operators

  • static_cast – Performs standard compile-time type conversions.
  • dynamic_cast – Performs runtime conversions in polymorphic class hierarchies.
  • const_cast – Adds or removes const and volatile qualifiers.
  • reinterpret_cast – Performs low-level reinterpretation of memory or pointer types.

reinterpret_cast

Is telling to the compiler “from this point on interpret this set of bits into this type T*”