Dynamic Cast In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Dynamic Cast In C++

Dynamic Cast In C++

BLUF: Mastering Dynamic Cast In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Dynamic Cast In C++

C++ is renowned for its efficiency. Learn how Dynamic Cast In C++ enables low-level control and high-performance computing in the tutorial below.

The dynamiccast operator in C++ is utilized to convert a pointer or reference from one type to a different type. It is commonly employed to safely downcast a polymorphic type during runtime. For the dynamiccast operator to work, the class hierarchy of polymorphic types must contain at least one virtual function.

Syntax:

The syntax for using dynamic_cast is as follows:

Example

dynamic_cast<new_type>(expression)

Where "expression" represents the specific expression undergoing casting and "new_type" indicates the target type for the casting operation. It is essential that the expression includes a pointer or reference to a polymorphic type.

To validate the accuracy of the object under consideration or referred to, the dynamiccast operator conducts a runtime type verification on the specified newtype. If the conversion is not feasible, the dynamiccast operator will either provide a null pointer (for a pointer cast) or trigger a std::badcast exception (for a reference cast).

Example:

A code snippet showcasing the utilization of "dynamic_cast" for executing a downcast operation:

Example

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:

Output

Woof woof!

Explanation:

In this instance, we establish a class hierarchy comprising Animal, Dog, and Cat. Both Dog and Cat are subclasses of Animal, with Dog featuring a bark method and Cat featuring a meow method.

We instantiate a fresh instance of a Canine entity within the "main" function and allocate its location to a pointer of the Animal type. Subsequently, we endeavor to transform an Animal pointer into a Canine pointer through dynamic means. Due to the actuality that the subject being referred to is a Canine entity, the dynamic_cast operation proves successful and furnishes a valid Canine pointer. Following this, we verify that the Canine pointer is not a nullptr (meaning the conversion was effective) and trigger the bark method of the canine entity using dogPtr. Lastly, we release the Animal pointer, which consequently removes the Canine entity as well.

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 .

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience