How to use the C++ type conversion operator dynamic_cast?
In C++, `dynamic_cast` is a type-safe casting operator used to safely convert a base class pointer or reference to a derived class pointer or reference. It can check if the conversion is valid at runtime and return the correct pointer or reference.
The syntax of dynamic_cast is as follows:
dynamic_cast<new_type>(expression)
In this case, new_type is the target type to convert to, and expression is the pointer or reference to be converted.
When using dynamic_cast, the following conditions must be met:
- The conversion type must be a pointer or reference type, not a basic type.
- The converted type must be a class type, not a void pointer.
- There must be an inheritance relationship between the source type and the target type.
When using dynamic_cast, the following checks will be performed:
- If the conversion is successful, return the converted pointer or reference.
- If the conversion fails and the target type is a pointer type, return a null pointer.
- If the conversion fails and the target type is a reference type, it will throw a std::bad_cast exception.
Here is an example using dynamic_cast:
#include <iostream>
class Base {
public:
virtual void print() {
std::cout << "Base" << std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "Derived" << std::endl;
}
};
int main() {
Base* basePtr = new Derived;
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
derivedPtr->print(); // 输出 "Derived"
} else {
std::cout << "Failed to cast" << std::endl;
}
delete basePtr;
return 0;
}
In the given example, the Base class is a base class, and the Derived class is a derived class that inherits from the Base class. First, an object of the Derived class is created and assigned to a Base class pointer called basePtr. Then, dynamic_cast is used to convert basePtr into a pointer of type Derived class called derivedPtr. Since Derived class is a derived class of Base class, the conversion is valid and derivedPtr will point to an object of the Derived class. Finally, the print() function of derivedPtr is called, which outputs “Derived”.
It is important to note that dynamic_cast can only be used for polymorphic types (i.e. classes with virtual functions) because it requires type checking at runtime. Using dynamic_cast on non-polymorphic types will result in a compilation error.