Originally Posted by
C_ntua
Another question is this. Is dynamic_cast generally recommended to be used, or does it have to much an cost? Can its exception (wrong casting) be handled so the program doesn't crush?
And finally, lets say you have a pointer to a class A. You point it on a derived class B : A. Can you determine with a function if the pointer points at a class of a or B?
Generally you design your classes polymorphically so that you never have to cast down to a derived type, however in the rare cases where you do need to downcast, you can check the runtime type of the object before you perform the cast using 'typeid'.
Some compilers require you to use a special flag to turn on RTTI though. Also notice that I included a virtual destructor in the super class. If you don't include at least one virtual function, typeid() probably won't report the actual runtime type of the object. (As you probably already know though, you should always include at least a virtual destructor)
Code:
#include <iostream>
#include <typeinfo>
class Super
{
public:
virtual ~Super() {}
};
class Sub : public Super {};
int main()
{
Super *obj = new Super;
std::cout << typeid(*obj).name() << std::endl;
if (typeid(*obj) == typeid(Super))
std::cout << "Yes, this is a Super class." << std::endl;
else
std::cout << "No, this isn't a Super class." << std::endl;
delete obj;
obj = new Sub;
std::cout << typeid(*obj).name() << std::endl;
if (typeid(*obj) == typeid(Sub))
std::cout << "Yes, this is a Sub class." << std::endl;
else
std::cout << "No, this isn't a Sub class." << std::endl;
delete obj;
}