Type Casting
Implicit and explicit type conversions
Interview Relevant: Important for data manipulation
Type Casting in C++
Type casting converts a value from one type to another.
C++ Cast Operators
- static_cast: Safe, compile-time checked conversions
- dynamic_cast: Runtime-checked polymorphic conversions
- const_cast: Add or remove const qualifier
- reinterpret_cast: Low-level bit reinterpretation
Implicit vs Explicit
- Implicit: Automatic conversion by compiler
- Explicit: Programmer-specified conversion
Code Examples
Different types of casting in C++.
cpp
1// Implicit conversion
2int a = 10;
3double b = a; // int to double automatically
4
5// C-style cast (avoid in C++)
6double pi = 3.14159;
7int truncated = (int)pi; // 3
8
9// C++ style casts (preferred)
10double d = 3.14;
11int i = static_cast<int>(d); // 3
12
13// dynamic_cast for polymorphism
14class Base { virtual void foo() {} };
15class Derived : public Base {};
16Base* base = new Derived();
17Derived* derived = dynamic_cast<Derived*>(base);
18
19// const_cast
20const int x = 10;
21int* ptr = const_cast<int*>(&x); // Remove const