C++ RunTime Type Identification

From Schmid.wiki
Jump to: navigation, search

Here is an example of RTTI:

#include <iostream>
#include <cstdlib>
#include <typeinfo>
using namespace std;

class Thing { };
class Thingie : public Thing { };

int main(void) {

    Thing*   x = new Thing;
    Thingie* y = new Thingie;

    // typeinfo.name()
    cout << typeid(x).name() << endl; // outputs 'P5Thing'
                                      // (Pointer, 5 char name, 'Thing')
    cout << typeid(y).name() << endl; // outputs 'P7Thingie'

    // typeof and typeinfo.==
    typeof(x) z;
    if(typeid(z) == typeid(Thing*))    // z is a Thing
        cout << "z is a Thing" << endl;
    if(typeid(y) == typeid(Thing*))    // y is *NOT* a Thing
        cout << "y is a Thing" << endl;

    // casting
    try {
        Thing* s = dynamic_cast<Thing*>(y);
    } catch(bad_cast) {
        cerr << "bad cast" << endl;
    }
    if(typeid(s) == typeid(Thing*))    // s is a Thing
        cout << "s is a Thing" << endl;

    exit(EXIT_SUCCESS);
}
Personal tools