Type Casting Operators

Casting

C++ supports C's explicit type casting operations (new-type)value (C-style cast), or new-type(value) (Function-style cast), called regular cast. Regular cast is too lax, and often produces expected result.

Casting operators

C++ introduces 4 new type casting operators:

  1. const_cast(value),
  2. static_cast(value),
  3.  dynamic_cast(value), 
  4. reinterpret_cast(value) to regulate type casting. Although the old styles is still acceptable in C++, new styles are preferable.


static_cast

static_cast is used for force implicit conversion. It throws a type-cast error if the conversion fails.
You can use static_cast to convert values of various fundamental types, e.g., from double to int, from float to long.

dynamic_cast

dynamic_cast can be used to verify the type of an object at runtime, before performing the type conversion. It is primarily used to perform "safe downcasting"

The syntax is:
dynamic_cast(ptr)
It converts the pointer ptr to a pointer of the type Type, in runtime, if ptr is pointing to an object of Type, or its direct or indirect subclass. Otherwise, it returns 0, or null pointer.

You can use dynamic_cast in a condition to ascertain the type of the object, before performing certain operations.

const_cast

The const_cast can be used to drop the const label, so as to alter its contents (i.e., cast away the const-ness or volatile-ness). This is useful if you have a variable which is constant most of the time, but need to be changed in some circumstances. You can declare the variable as const, and use const_cast to alter its value. The syntax is:

const_cast(expression)
const_cast cannot change the type of an object.

reinterpret_cast

Used for low-level casts that yield implementation-dependent result, e.g., casting a pointer to an int.

Comments

Popular posts from this blog

Covid-19 Analysis and Visualization using Plotly Express

Artificial Intelligence (Problem Solving)

Linear Regression