Using __try_cast for Dynamic Casting

Using __try_cast for Dynamic Casting

C++ supports the idea of casting, wherein you tell the compiler to convert one type into another to use it in an expression. Although casting can be useful, it can also be dangerous, and the __try_cast keyword has been introduced in the Managed Extensions for C++ to help make the operation safer. The following code fragment shows both safe and unsafe casting:

// Define the Vehicle and Car classes __gc class Vehicle {}; __gc class Car : public Vehicle {}; __gc class Truck : public Vehicle {}; __gc class Bus : public Vehicle {}; ... Car* pc = new Car(); // Create a Car Vehicle* pv = pc; // Point to it using a Vehicle pointer - // OK ... Car* pc2 = pv; // Copy pv into another Car* pointer - // not OK!

The compiler raises an error on the last line, complaining that it can’t convert a Vehicle* to a Car*. The problem is that a Vehicle pointer could point to any object derived from Vehicle, such as a Truck or a Bus. Implicitly casting from a Car to a Vehicle is fine because a Car is a Vehicle; going the other way doesn’t work because not every Vehicle is a Car. The way around this issue is to use the __try_cast construct, like this:

try { Car* pc2 = __try_cast<Car*>(pv); } catch(System::InvalidCastException* pce) { Console::WriteLine("Cast failed"); }

At run time, __try_cast checks the object on the other end of the pointer to see if it has the same type as the object you’re trying to cast to. If it does, the cast works; if it doesn’t, an InvalidCastException is thrown.


dynamic_cast construct supported by standard C++. The difference is that __try_cast throws an exception if the cast fails.

Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
Year: 2003
Pages: 208 © 2008-2017.
If you may any questions please contact us: