Sobes.tech
Junior — Middle

What types of type casting do you know and have used in your practice?

sobes.tech AI

Answer from AI

In C++, there are several types of type casting:

  • static_cast — used for standard conversions, such as between numeric types, pointers in an inheritance hierarchy, and for explicitly calling a conversion constructor.
  • dynamic_cast — used for safe casting of pointers or references within an inheritance hierarchy, with type checking at runtime (RTTI). Returns nullptr on failure for pointers.
  • const_cast — allows removing or adding the const or volatile qualifier.
  • reinterpret_cast — performs low-level type conversions, such as between unrelated pointer types, without safety checks.

In practice, static_cast is most often used for converting numeric types and pointers within an hierarchy, const_cast for removing const when necessary, and dynamic_cast for safe casting in polymorphic classes.

Example of using static_cast:

int i = 10;
double d = static_cast<double>(i);

Example of dynamic_cast:

class Base { virtual void foo() {} };
class Derived : public Base {};

Base* b = new Derived();
Derived* d = dynamic_cast<Derived*>(b);
if (d) {
    // Casting succeeded
}