Learn C++
#include "variablesdatatypes/type_conversion.hpp"

Type Conversion & Casting in C++

//concept

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.

//how it works
1

Implicit promotion

In mixed expressions the narrower type promotes to the wider one (int to double), preserving value before the arithmetic happens.

2

static_cast: the everyday cast

static_cast<double>(votes) / total forces floating-point division — checked at compile time, explicit about intent.

3

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.

4

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.

//example
#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;
}
Output
3.5, 3
1Without the cast, 7 / 2 would be integer division giving 3; casting votes to double first promotes the whole division.
2static_cast<int>(3.99) truncates toward zero to 3 — the cast makes the deliberate data loss visible.
3Both results print as computed, showing promotion in one line and narrowing in the other.
//use cases
Fixing integer-division bugs in averages and percentages with one static_cast
Downcasting a Base* to Derived* safely with dynamic_cast instead of hoping
Letting braced initialization reject narrowing at compile time in new code
Replacing every C-style (type)value cast with a named cast that states its purpose

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.