📜  cast c++ (1)

📅  最后修改于: 2023-12-03 15:14:06.647000             🧑  作者: Mango

Cast in C++

C++ provides several types of casts, also called type conversions, which allow a value of one data type to be converted to another data type. The process of converting a value from one data type to another is known as casting.

Casting can be used for various purposes, such as:

  • Changing the data type of a variable
  • Converting a derived class pointer to a base class pointer
  • Casting a void pointer to another type of pointer
  • Performing arithmetic operations with values of different data types
Syntax of Casting

The syntax for casting in C++ is as follows:

new_type(expression)

Here, new_type is the target data type, and expression is the value to be cast.

There are four types of casting available in C++:

  1. Static Cast: This is the most commonly used type of cast in C++. It is used to convert a value from one data type to another data type. It checks if the casting is valid during compile time.

    new_type = static_cast<new_type>(expression);
    
  2. Dynamic Cast: This is used for casting a pointer or reference to a base class to a derived class (downcast). It checks if the casting is valid during runtime.

    new_type = dynamic_cast<new_type>(expression);
    
  3. Const Cast: This is used to remove the const or volatile qualifier from a variable. It can be used to cast a non-const variable to a const variable, but not vice versa.

    new_type = const_cast<new_type>(expression);
    
  4. Reinterpret Cast: This is used to convert a pointer to any other pointer type, even if the source pointer and destination pointer are of different types. It should be used with caution as it may lead to undefined behavior.

    new_type = reinterpret_cast<new_type>(expression);
    
Examples
Static Cast
// Converting an int to double using static_cast
int myInt = 10;
double myDouble = static_cast<double>(myInt);
Dynamic Cast
// Casting a base class pointer to a derived class pointer using dynamic_cast
class BaseClass { /* ... */ };
class DerivedClass : public BaseClass { /* ... */ };

BaseClass* basePtr = new DerivedClass();
DerivedClass* derivedPtr = dynamic_cast<DerivedClass*>(basePtr);
Const Cast
// Removing const from a variable using const_cast
const int myConst = 10;
int myNonConst = const_cast<int>(myConst);
Reinterpret Cast
// Casting an int pointer to a char pointer using reinterpret_cast
int* myIntPtr = new int[10];
char* myCharPtr = reinterpret_cast<char*>(myIntPtr);