Type Casting in C++
C-style casting ((int)value) C++ mein bhi kaam karta hai, lekin discouraged hai kyunki ye bahut "powerful" hai (kuch bhi kisi bhi type mein force kar sakta hai) — agar galti se galat cast ho jaaye, compiler warn nahi karega.
C++ 4 alag cast operators deta hai: static_cast (normal, compile-time safe conversions jaise int-to-float), dynamic_cast (runtime-safe conversions class hierarchies mein, aage polymorphism mein aayega), const_cast (const hataane ke liye), reinterpret_cast (low-level, dangerous bit reinterpretation).
double d = 3.14;
int i = static_cast<int>(d); // preferred over (int)d
cout << i << endl; // 3
// C-style (works, but discouraged in modern C++):
int j = (int)d;- static_cast = normal, safe conversions (preferred)
- dynamic_cast = runtime-safe, class hierarchies ke liye
- C-style cast kaam karta hai, lekin modern C++ mein avoid karo
Implicit conversion automatically hoti hai (jaise int ko double mein assign karna) — koi data loss na ho to safe hai. Explicit conversion (casting) tab zaroori hai jab possibly data loss ho (double ko int mein, jaha decimal part chhoot jaayega) — compiler warning deta hai bina explicit cast ke.
int i = 10;
double d = i; // implicit — safe, koi data loss nahi
double pi = 3.14;
int truncated = static_cast<int>(pi); // explicit — 3 (decimal chala gaya)
cout << truncated << endl;