21.6 The dynamic_cast Operator

I l @ ve RuBoard

The dynamic_cast operator can be used to change a pointer or reference to a base class to that of the derived class and vice versa. This conversion is done in a safe manner. If you attempt to do an incorrect conversion, an exception is thrown. By default this aborts the program. (See Chapter 22 for information on exceptions.)

For example:

 class room { ... }; class office: public class room { ... } class garage: public class room { ... }  void funct(room *ptr) {     // Correct and safe conversion -- no problem     office *office_ptr = dynamic_cast<office *>(ptr);     // Incorrect conversion -- throws an exception     garage *other_ptr = dynamic_cast<office *>(ptr); ... } int main(  ) {     office the_office;     funct(&the_office); 

The call to funct changes a pointer to a derived class ( office ) into a pointer to the base class ( room ). This is done automatically by C++.

The first dynamic_cast converts the pointer back to a pointer to the correct derrived class. The second tries to convert the object into a garage . Since the actual object is an office , the conversion fails and an exception is thrown.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net