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 |