Home > Development > C++ Runtime Type Identification – RTTI Basics

C++ Runtime Type Identification – RTTI Basics


Well this is a basic first look at C++ type identification from a C# developers point of view. In .NET we have a fairly nice and easy Reflection API that allows type inspection of elements using the typeof operator or the GetType method on types. C++ provides a typeid method that allows you to access a const type_info& type that you can then access the name method. I am still investigating additional functionality equivalent to the Activator.CreateInstance and friends and accessing methods but this is a quick primer on getting started. There will be a follow up on more advanced RTTI in C++.

And now some code.

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

class Super{
public:
    virtual void printMessage();
};

class Sub : public Super{
public:
    virtual void printMessage();
};

void Super::printMessage(){
    cout << "Super Message" << endl;
}

void Sub::printMessage(){
    cout << "Sub Message" << endl;
}

void printTypeName(Super* ptr){
    const type_info& info = typeid(Super);
    cout << "Name: " << info.name() << endl;

    if(typeid(Super) == typeid(*ptr)){
        cout << "Its really is a super" << endl;
    }
}

int main(int argc, char *argv[])
{
    Super* super = new Super();
    printTypeName(super);

    Super* ref = new Sub();
    printTypeName(ref);

    delete super;
    delete ref;
    return 0;
}

Blair…

Advertisements
Categories: Development Tags: , , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: