CPlusPlus Type Casting
From Stack Overflow
Contents |
dynamic_cast
Cast a derived class to a base class.
class CBase { };
class CDerived: public CBase { };
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived
static_cast
Either direction, but when going from base to derived, the programmer needs to ensure that the pointer really is to the derived class.
reinterpret_cast
Anything to anything (...probably not a great idea...)
const_cast
Add or remove the "const" prefix (...probably not a great idea...)
typeid
Allows looking at an object's type information at runtime (e.g. introspection).
// typeid
#include <iostream>
#include <typeinfo>
using namespace std;
int main () {
int * a,b;
a=0; b=0;
if (typeid(a) != typeid(b))
{
cout << "a and b are of different types:\n";
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
}
return 0;
}
Prints:
a and b are of different types: a is: int * b is: int
// typeid, polymorphic class
#include <iostream>
#include <typeinfo>
#include <exception>
using namespace std;
class CBase { virtual void f(){} };
class CDerived : public CBase {};
int main () {
try {
CBase* a = new CBase;
CBase* b = new CDerived;
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
cout << "*a is: " << typeid(*a).name() << '\n';
cout << "*b is: " << typeid(*b).name() << '\n';
} catch (exception& e) { cout << "Exception: " << e.what() << endl; }
return 0;
}
Prints:
a is: class CBase * b is: class CBase * *a is: class CBase *b is: class CDerived

