The casting operator dynamiccast in C++ is used to change a pointer or reference from one type to another type. A polymorphic type can be safely downcast at runtime using the dynamiccast operator . The class hierarchy of polymorphic types includes at least one virtual function.
Syntax:
The syntax for using dynamic_cast is as follows:
dynamic_cast<new_type>(expression)
Where "expression" is the expression that is being cast and "new_type" denotes the type to which the expression is being cast. A pointer or reference to a polymorphic type must be present in the expression.
To confirm that the object being addressed to or referenced is true of the specified newtype , the dynamiccast operator will perform a runtime type check. The dynamiccast operator will return a null pointer (for a pointer cast) or throw a std::badcast exception (for a reference cast) if the conversion is impossible.
Example:
A code snippet that demonstrates how to use " dynamic_cast " to perform a downcast:
class Animal {
public:
virtual ~Animal() {}
};
class Dog : public Animal {
public:
void bark() {
std::cout<< "Woof woof!" <<std::endl;
}
};
class Cat : public Animal {
public:
void meow() {
std::cout<< "Meow meow!" <<std::endl;
}
};
int main() {
Animal* animalPtr = new Dog;
Dog* dogPtr = dynamic_cast<Dog*>(animalPtr);
if (dogPtr != nullptr) {
dogPtr->bark();
}
delete animalPtr;
return 0;
}
Output:
Woof woof!
Explanation:
In this example, we create a hierarchy of classes: Animal, Dog, and Cat . Dog and Cat both inherit from Animal , and Dog has a function called bark , while Cat has a function called meow .
We create a new Dog object in the "main" and assign its address to a pointer of type Animal . After that, we try to convert an Animal pointer to a Dog pointer using dynamics. Because the objeccpp tutorialed to is a Dog object, dynamic_cast succeeds and returns a valid Dog pointer . After that, we check that the Dog pointer is not a nullptr (ie, the conversion was successful) and call the dog object's bark function with dogPtr . Finally, we delete the Animal pointer , which also deletes the Dog object .
Note: Dynamic_cast is only intended for use with polymorphic types and should not be used with non-polymorphic types. Additionally, the use of dynamic_cast should be minimized, as it can be a sign of poor design in the class hierarchy. In general, it's better to use virtual functions and inheritance to achieve the desired behaviour, rather than relying on casting.
Some importancpp tutorials of Dynamic_cast operator are as follows:
- dynamiccast can also be used with references instead of pointers. The syntax is the same as for pointers, except that you replace the pointer notation * with the reference notation &. For example: dynamiccast(expression) .
- If dynamiccast is used to cast a pointer or reference to a class type to a void pointer or reference , it will perform a reinterpretcast instead of a dynamic_cast .
- dynamic_cast can only be used with pointers or references, not with values.
- The performance of dynamic_cast can be slower than other types of casts due to the required runtime type checking.
- dynamic_cast can only be used with classes that have at least one virtual function in their class hierarchy. This is because the virtual function table (vtable) is used to perform the runtime type check.
- dynamiccast can be used to cast from a derived class to a base class, but it is not recommended. Instead, use staticcast or rely on implicit conversion.
- If dynamic_cast is used to cast a null pointer to a pointer type, the result will be a null pointer of the target type.
- When using dynamiccast with pointers, if the cast fails (i.e., the pointer is not of the target type), the result will be a null pointer. It is different from reinterpretcast, which will perform an unchecked cast that could result in undefined behavior.
- If the cast fails using dynamiccast with references, a badcast exception will be thrown. Therefore, it's important to use exception handling to catch and handle this exception appropriately.
- dynamiccast can also be used to perform cross-casting, which involves casting between two unrelated classes that share a common base class. For example, suppose you have two classes A and B , both of which inherit from a common base class C . If you have a pointer or reference to an A object and you want to cast it to a B pointer or reference (or vice versa), you can use dynamiccast . However, this type of casting can be tricky and requires careful consideration of the class hierarchy.
- dynamic_cast is a relatively expensive operation, so it should be used effectively in performance-critical code. In some cases, it may be better to use alternative techniques, such as template Meta programming or compile-time polymorphism .