# Type Casting in C++ — static_cast, dynamic_cast, const_cast and reinterpret_cast

Source: https://skills101.in/learn/cpp/cpp-type-casting — Skills101 free tutorial (C++ Programming). Updated 2026-11-21.

A program often needs a value as a different type: total marks as a `double` to get an exact average, a character as its ASCII code, a base-class pointer as the derived class it really points to. Converting a value from one type to another is called **type casting** (or type conversion). C++ gives four **named casts** for this, each with one clear job. "What are the four casts in C++, and when is each used?" is a standard interview question.

## 1. Implicit conversions

Many conversions happen **automatically**. The compiler converts `int` to `double` when you mix them, `char` to `int` in arithmetic, and a derived-class pointer to a base-class pointer.

The trouble is that the automatic rules do not always do what you mean. The classic example is integer division:

```cpp
#include <iostream>
using namespace std;

int main() {
    int total = 355, subjects = 4;
    double avg1 = total / subjects;                        // int / int = 88, then converted
    double avg2 = static_cast<double>(total) / subjects;   // 355.0 / 4 = 88.75
    cout << avg1 << " " << avg2 << "\n";

    char grade = 'A';
    cout << static_cast<int>(grade) << " " << static_cast<char>(grade + 2) << "\n";

    double price = 99.99;
    int rupees = static_cast<int>(price);                  // drops the fraction
    cout << rupees << "\n";
    return 0;
}
```

```text
88 88.75
65 C
99
```

In `avg1`, both operands are `int`, so C++ does **integer division** first (88) and only then converts 88 to `double`. Casting one operand **before** dividing makes it a floating-point division. Converting `double` to `int` **truncates** — it drops the fraction, it does not round.

## 2. Why not the C-style cast?

C writes casts as `(double)total`. C++ still accepts this, but it is discouraged because:

1. It can do **anything** — a harmless number conversion, removing `const`, or treating memory as a completely different type — and the code looks the same in every case.
2. It is hard to **search** for. You cannot easily grep a project for `(int)`.

The four named casts each allow only one kind of conversion, so the compiler rejects a cast that does something you did not intend, and a reader sees your intent at once.

![Table of the four C++ casts: static_cast for ordinary conversions checked at compile time, dynamic_cast for safe downcasting checked at run time, const_cast to remove const, and reinterpret_cast to reinterpret raw bits](https://skills101.in/learn-img/cpp/four-casts.svg)

## 3. static_cast: ordinary, compile-time conversions

`static_cast<T>(x)` is the one you will use most. It handles conversions that make sense and are checked by the compiler:

- between number types: `int` ↔ `double`, `char` ↔ `int`
- `enum class` values to and from integers
- `void *` back to a typed pointer (for example, after `malloc`)
- **upcasts** (derived → base) and, without any run-time check, downcasts

```cpp
#include <iostream>
using namespace std;

enum class Grade { A = 1, B, C };

int main() {
    Grade g = Grade::C;
    cout << static_cast<int>(g) << "\n";                 // enum class needs an explicit cast
    Grade h = static_cast<Grade>(2);
    cout << (h == Grade::B) << "\n";

    long long big = 3000000000LL;
    int small = static_cast<int>(big);                   // allowed, but the value does not fit
    cout << (small == big) << "\n";
    return 0;
}
```

```text
3
1
0
```

The last line is a warning: `static_cast` does what you ask even when information is lost. Three billion does not fit in a 32-bit `int`, so the result is a different number. A cast tells the compiler "I know what I am doing" — so be sure you do.

## 4. dynamic_cast: safe downcasting

An **upcast** goes from derived to base (`Manager *` → `Employee *`). It is always safe and happens automatically. A **downcast** goes the other way, from base to derived. It is only safe if the object really **is** of the derived type.

`dynamic_cast` checks this **at run time**:

- For pointers, it returns the derived pointer if the object matches, or **`nullptr`** if it does not.
- For references, it throws **`std::bad_cast`** if it does not match (a reference cannot be null).
- It only works on **polymorphic** classes — classes with at least one virtual function — because it uses the type information stored with the vtable.

```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Employee {
public:
    string name;
    Employee(string n) : name(n) {}
    virtual ~Employee() {}                    // makes the class polymorphic
};

class Manager : public Employee {
public:
    int teamSize;
    Manager(string n, int t) : Employee(n), teamSize(t) {}
};

class Engineer : public Employee {
public:
    Engineer(string n) : Employee(n) {}
};

int main() {
    vector<Employee *> staff = {new Engineer("Asha"), new Manager("Ravi", 6), new Engineer("Meena")};
    for (Employee *e : staff) {
        if (Manager *m = dynamic_cast<Manager *>(e))
            cout << m->name << " manages " << m->teamSize << " people\n";
        else
            cout << e->name << " is not a manager\n";
    }
    for (Employee *e : staff) delete e;
    return 0;
}
```

```text
Asha is not a manager
Ravi manages 6 people
Meena is not a manager
```

![An Employee pointer can point to an Engineer or a Manager. dynamic_cast to Manager returns a valid pointer for the Manager object and nullptr for the Engineer objects](https://skills101.in/learn-img/cpp/dynamic-cast.svg)

If we had used `static_cast<Manager *>(e)` here, the compiler would have trusted us. For Asha, an `Engineer`, reading `m->teamSize` would then read memory that is not a `teamSize` at all — undefined behaviour. `dynamic_cast` costs a small run-time check, and that check is what makes it safe.

If you find yourself writing many `dynamic_cast`s, consider a virtual function instead: let each class answer the question itself.

## 5. const_cast: removing const

`const_cast` adds or removes `const`. Its honest use is calling an old function (often a C library) that takes a `char *` but does **not** actually modify the data:

```cpp
#include <iostream>
#include <string>
using namespace std;

void legacy_print(char *s) { cout << "[" << s << "]\n"; }   // old API: does not change s

int main() {
    const string city = "Jaipur";
    legacy_print(const_cast<char *>(city.c_str()));          // we know it only reads
    return 0;
}
```

```text
[Jaipur]
```

**Modifying** an object that was declared `const` through a `const_cast` pointer is undefined behaviour. The cast only removes the compiler's check; it does not make the object writable.

## 6. reinterpret_cast: the same bits as a different type

`reinterpret_cast` tells the compiler to treat a pointer as a pointer to a completely unrelated type. It does no conversion of the data at all. It is used in low-level code: binary file I/O (as in the file handling lesson), hardware registers and network packets.

```cpp
#include <iostream>
using namespace std;

int main() {
    int x = 0x01020304;
    unsigned char *bytes = reinterpret_cast<unsigned char *>(&x);
    for (int i = 0; i < 4; i++) cout << (int)bytes[i] << " ";
    cout << "\n";
    return 0;
}
```

```text
4 3 2 1
```

The output shows how the `int` is laid out in memory. On a **little-endian** machine (x86 and most ARM systems, which covers nearly all laptops and phones), the lowest byte is stored first, giving `4 3 2 1`. A big-endian machine would print `1 2 3 4`. That machine dependence is exactly why `reinterpret_cast` should be rare.

## 7. explicit constructors: stopping surprise conversions

A constructor with one parameter also acts as an **implicit conversion**. With `class Rupees { public: Rupees(int v); };`, the call `pay(500)` silently turns `500` into a `Rupees` object. Sometimes that hides a bug — was 500 rupees or 500 paise meant? Mark the constructor **`explicit`** to forbid it:

```cpp
class Rupees {
public:
    explicit Rupees(int v) : value(v) {}
    int value;
};

void pay(Rupees r) { /* ... */ }

// pay(500);            // error: no implicit conversion from int
// pay(Rupees(500));    // OK: the conversion is written out
```

A good rule: make single-argument constructors `explicit` unless the implicit conversion is clearly natural.

## Common mistakes

- Casting after an integer division (`(double)(a / b)`) instead of before (`static_cast<double>(a) / b`).
- Expecting `double` → `int` to round. It truncates: 99.99 becomes 99.
- Using `static_cast` to downcast when you are not sure of the real type. Use `dynamic_cast` and check for `nullptr`.
- Using `dynamic_cast` on a class with no virtual functions — it does not compile.
- Writing through a pointer obtained by `const_cast` on a truly `const` object.
- Reaching for C-style casts out of habit; they hide which conversion you meant.

## Quick recap

- Implicit conversions are automatic; be careful with integer division and narrowing.
- `static_cast`: normal conversions (numbers, enums, upcasts), checked at compile time.
- `dynamic_cast`: safe downcast checked at run time; `nullptr` for pointers, `bad_cast` for references; needs a virtual function.
- `const_cast`: removes `const` to call old APIs; never use it to modify a const object.
- `reinterpret_cast`: raw reinterpretation of bits; machine-dependent, use rarely.
- `explicit` constructors stop unwanted implicit conversions.


Practice quiz and free certificate: https://skills101.in/learn/cpp/cpp-type-casting