The Wayback Machine - https://web.archive.org/web/20240717024424/https://www.geeksforgeeks.org/casting-operators-in-cpp/
Open In App

Casting Operators in C++

Last Updated : 12 Mar, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Casting operators are used for type casting in C++. They are used to convert one data type to another. C++ supports four types of casts:

  1. static_cast
  2. dynamic_cast
  3. const_cast
  4. reinterpret_cast

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 of static_cast

static_cast <new_type> (expression);

where,

  • expression: 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 of static_cast

C++
// C++ program to illustrate the static_cast
#include <iostream>
#include <typeinfo>
using namespace std;

int main()
{

    int num = 10;

    // converting int to double
    double numDouble = static_cast<double>(num);

    // printing data type
    cout << typeid(num).name() << endl;

    // typecasting
    cout << typeid(static_cast<double>(num)).name() << endl;

    // printing double type t
    cout << typeid(numDouble).name() << endl;

    return 0;
}

Output
i
d
d

In this example, we have included the “typeinfo” library so that we can use typeid() function to check the data type. We have defined an integer variable ‘num’ and converted it into a double using static_cast. After that, we print the data types of variables and pass static_cast<double>(num) in typeid() function 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). It ensures type safety by performing a runtime check to verify the validity of the conversion.

Syntax of dynamic_cast

dynamic_cast <new_type> (expression);

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 of dynamic_cast

C++
// C++ program to illustrate the dynamic_cast
#include <iostream>
using namespace std;

// Base Class
class Animal {
public:
    virtual void speak() const
    {
        cout << "Animal speaks." << endl;
    }
};

// Derived Class
class Dog : public Animal {
public:
    void speak() const override
    {
        cout << "Dog barks." << endl;
    }
};

// Derived Class
class Cat : public Animal {
public:
    void speak() const 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 for const_cast

const_cast <new_type> (expression);

Example of const_cast

C++
// C++ program to illustrate the const_cast
#include <iostream>
using namespace std;

int main()
{

    const int number = 5;
    // Pointer to a const int
    const int* ptr = &number;

    // 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 << "Modified number: " << *nonConstPtr;

    return 0;
}

Output
Modified number: 10

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 of reinterpret_cast

reinterpret_cast <new_type> (expression);

Example

C++
// C++ program to illustrate the reinterpret_cast
#include <iostream>
using namespace std;

int main()
{
    int number = 10;
    // Store the address of number in numberPointer
    int* numberPointer = &number;

    // Reinterpreting the pointer as a char pointer
    char* charPointer
        = reinterpret_cast<char*>(numberPointer);

    // Printing the memory addresses and values
    cout << "Integer Address: " << numberPointer << endl;
    cout << "Char Address: "
         << reinterpret_cast<void*>(charPointer) << endl;

    return 0;
}

Output
Integer Address: 0x7fff64789f1c
Char Address: 0x7fff64789f1c

In the above example, we have defined an int variable ‘number’ and then store the address of ‘number’ in ‘numberPointer’ of the int type after that we have converted the ‘numberPointer’ of the int type into char pointer and then store it into ‘charPointer’ variable. To verify that we have printed the address of both numberPointer and charPointer. To print the address stored in ‘charPointer’ reinterpret_cast<void*> is used to bypass the type-checking mechanism of C++ and allow the pointer to be printed as a generic memory address without any type-specific interpretation.

Note: const_cast and reinterpret_cast are generally not reccommended as they vulnerable to different kinds of errors.



Previous Article
Next Article

Similar Reads

reinterpret_cast in C++ | Type Casting operators
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.It does not check if the pointer type and data pointed by the pointer is same or not. Syntax : data_type *var_name = reinterpret_cast &lt;
3 min read
const_cast in C++ | Type Casting operators
C++ supports following 4 types of casting operators: 1. const_cast 2. static_cast 3. dynamic_cast 4. reinterpret_cast 1. const_cast const_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast. 1) const_cast can be used to change non-const class members inside a const member function. Consider th
4 min read
Conversion Operators in C++
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading function in class.For example consider the follow
2 min read
unordered_set operators in C++ STL
Unordered_set provides two operators in C++ STL. These are: Syntax: 1. (unordered_set &amp;lhs == unordered_set &amp;rhs) 2. (unordered_set &amp;lhs != unordered_set &amp;rhs) These operators are discussed in detail below: unordered_set == operator in C++ STL The ‘==’ is an operator in C++ STL performs equality comparison operation between two unor
5 min read
C++ Pointer Operators
Prerequisite: Pointers in C++ A pointer variable is a variable that stores the address of another variable or in other a pointer variable points to the variable whose address is stored inside it. Syntax: int *pointer_name; There are mainly two types of Pointer operators mainly used: Address of operator (&amp;)The indirection operator/Dereference op
2 min read
C++ Arithmetic Operators
Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction, ‘*’ is used for multiplication, etc. In simple terms, arithmetic operators are used to perform arithmetic operations on variables and data; they follow the same relationship betwe
3 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(&gt;&gt;/&lt;&lt;) Overloading in C++ We can't directly use the Input/Output Operators (&gt;
2 min read
C++ Increment and Decrement Operators
Prerequisite: Operators in C++ What is a C++ increment Operator? The C++ increment operator is a unary operator. The symbol used to represent the increment operator is (++). The increment operator increases the value stored by the variable by 1. This operator is used for Numeric values only. There are two types of C++ increment Operator: Pre-Increm
4 min read
C++ Comparison Operators
Comparison operators are operators used for comparing two elements, these are mostly used with if-else conditions as they return true-false as result. There are mainly 6 Comparison Operators namely: Greater than (&gt;) : this operator checks whether operand1 is greater than operand2. If the result turns out to be true, it returns true or else retur
3 min read
C++ Relational Operators
In C++ programming language, we sometimes require to compare values and expressions. This comparison allows us to determine relationships, make decisions, and control the flow of our programs. The relational operators in C++ provide the means to compare values and evaluate conditions. In this article, we will learn about C++ relational operators an
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg