Cast operators in C++

Cast operators in C++

There are four types of cast operators in C++:

static_cast
dynamic_cast
const_cast
reinterpret_cast

Static_cast:

#include 
using namespace std;
int main () {
    
    double d = 3415.3124;  
    int i = static_cast(d);
    cout <<"d= " <

Output:

d= 3415.31
i= 3415

dynamic_cast:

dynamic_cast is used for downcasting in polymorphism. It requires at least one virtual function in the base class. It returns nullptr if the cast fails.

class Base { virtual void func() {} };
class Derived : public Base {};
Base* b = new Derived;
Derived* d = dynamic_cast(b);  // Downcasting

const_cast:

Removes const or volatile qualifier from a variable.

void func(const int* p) {
    int* q = const_cast(p);  // Removes const
    *q = 20;  // Modifies the value (UB if originally constant)
}

reinterpret_cast:

Converts one type to another regardless of compatibility. It is used for low-level memory operations.

int a = 65;
char* c = reinterpret_cast(&a);  // Treats int as char*

No Comments

Leave a Reply