Casting Operators in C++ (original) (raw)
Last Updated : 05 May, 2025
The **casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called **typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).
Let's take a look at an example:
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { char c = 'a';
// Converting c from char to int
int i = static_cast<int>(c);
// Printing the converted value
cout << i;
return 0;
}
`
**Explanation: We have converted the character **c it an integer corresponding to its ASCII value by using casting operator.
In the above code, static_cast<> operator is used. C++ provides 4 such types of casting operators:
Table of Content
1. static_cast
The**static_cast operator is the most commonly used casting operator in C++. It performs compile-time type conversion and is mainly used for explicit conversions that are considered safe by the compiler.
**Syntax
**static_cast <__new_type_> (exp);
where,
- **exp: Data to be converted.
- **new_type: Desired type of expression
The static_cast can be used to convert between related types, such as numeric types or pointers in the same inheritance hierarchy.
**Example
C++ `
#include <bits/stdc++.h> using namespace std;
int main() {
int n = 10;
// converting int to double
double nd = static_cast<double>(n);
// printing data type
cout << typeid(n).name() << endl;
// typecasting
cout << typeid(static_cast<double>(n)).name() << endl;
// Printing double type
cout << typeid(nd).name();
return 0;
}
`
**Explanation: In this example, we have used **typeid() operator to check the data type. We have defined an integer variable **n and converted it into a double using **static_cast. After that, we print the data types of variables and pass **static_cast(n) in **typeid() to check its data type. we can see the output ****"i, d, d"** is printed where **i denotes **integer and **d denotes **double.
2. dynamic_cast
The dynamic_cast operator is mainly used to perform downcasting (converting a pointer/reference of a base class to a derived class) in polymorphisms and inheritance. It ensures type safety by performing a runtime check to verify the validity of the conversion.
**Syntax
**dynamic_cast <__new_type_> (exp);
If the conversion is not possible, **dynamic_cast returns a **null pointer (for pointer conversions) or throws a **bad_cast exception (for reference conversions).
**Example
C++ `
#include using namespace std;
// Base Class class Animal { public: virtual void speak() { cout << "Animal speaks." << endl; } };
// Derived Class class Dog : public Animal { public: void speak() override { cout << "Dog barks." << endl; } };
// Derived Class class Cat : public Animal { public: void speak() override { cout << "Cat meows." << endl; } };
int main() {
// Base class pointer to derived class object
Animal* animalPtr = new Dog();
// Downcasting
Dog* dogPtr = dynamic_cast<Dog*>(animalPtr);
// Checking if the typecasting is successfull
if (dogPtr) {
dogPtr->speak();
}
else {
cout << "Failed to cast to Dog." << endl;
}
// Typecasting to other dervied class
Cat* catPtr = dynamic_cast<Cat*>(animalPtr);
if (catPtr) {
catPtr->speak();
}
else {
cout << "Failed to cast to Cat." << endl;
}
delete animalPtr;
return 0;
}
`
Output
Dog barks. Failed to cast to Cat.
**Explanation: The first line of output is printed because the **animalPtr of the **Animal type is successfully cast to the **Dog type and **speak() function of the Dog class is invoked but the casting of the **Animal type to 'Cat' type is failed because **animalPtr points to a **Dog object thus, the dynamic cast fails because the typecasting is not safe.
3. const_cast
The **const_cast operator is used to modify the const or volatile qualifier of a variable. It allows programmers to temporarily remove the constancy of an object and make modifications. Caution must be exercised when using const_cast, as modifying a const object can lead to undefined behavior.
**Syntax
**const_cast <__new_type_> (exp);
**Example
C++ `
#include using namespace std;
int main() {
const int n = 5;
// Pointer to a const int
const int* ptr = &n;
// int* nonConstPtr = ptr; if we use this
// instead of without using const_cast
// we will get error of invalid conversion
int* nonConstPtr = const_cast<int*>(ptr);
*nonConstPtr = 10;
cout << *nonConstPtr;
return 0;
}
`
**Explanation: In the above example, we have modified the value of the **const type pointer by changing its qualifier from **const to **non-const and then printing the modified value.
4. reinterpret_cast
The **reinterpret_cast operator is used to convert the pointer to any other type of pointer. It does not perform any check whether the pointer converted is of the same type or not.
**Syntax
**reinterpret_cast <__new_type_> (exp);
**Example
C++ `
#include using namespace std;
int main() { int n = 10;
// Store the address of number in nptr
int* nptr = &n;
// Reinterpreting the pointer as a char pointer
char* charptr = reinterpret_cast<char*>(nptr);
// Printing the memory addresses and values
printf("Integer Address: %p\n", nptr);
printf("Char Address: %p", charptr);
return 0;
}
`
Output
Integer Address: 0x7ffca2a2980c Char Address: 0x7ffca2a2980c
**Explanation: In the above example, we have defined an int variable **n and then store the address of **n in **nptr of the int type after that we have converted the nptr of the int type into char pointer and then store it into **charptr variable. To verify that we have printed the address of both **nptr and **charptr. **printf is used as **cout assumes that **char* is a **string and tries to print its characters leading to undefined errors.
**Note: **const_cast and **reinterpret_cast are generally not recommended as they vulnerable to different kinds of errors.