Type Conversion & Casting in C++
C++ converts between types implicitly (int to double in mixed arithmetic) and explicitly through casts. The old C-style cast (int)x still works but hides intent, so modern C++ prefers four named casts: static_cast for sensible conversions, dynamic_cast for safe downcasting along inheritance, const_cast for adding/removing const, and reinterpret_cast for raw bit reinterpretation.
Narrowing — squeezing a value into a type that can't hold it, like double into int — drops data silently with old-style initialization, warns with = , and is rejected outright by braced initialization. Reaching for static_cast documents that the conversion is deliberate.
Implicit promotion
In mixed expressions the narrower type promotes to the wider one (int to double), preserving value before the arithmetic happens.
static_cast: the everyday cast
static_cast<double>(votes) / total forces floating-point division — checked at compile time, explicit about intent.
The other three casts
dynamic_cast safely navigates class hierarchies (returns nullptr on failure for pointers); const_cast adjusts constness; reinterpret_cast reinterprets raw bits and is rarely needed.
Narrowing rules
Braced lists reject narrowing (int x{3.5}; won't compile), = warns, and C-style casts silence everything — prefer braces plus static_cast.
#include <iostream> int main() { int votes = 7, total = 2; double ratio = static_cast<double>(votes) / total; int chopped = static_cast<int>(3.99); std::cout << ratio << ", " << chopped << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.