2

In C++ you can declare a pointer as one type, and then point it towards a different, inheriting type instead. Is there any way to tell which you're currently pointing at?

#include <typeinfo>
using namespace std;

class Foo
{
};

class Bar : public Foo
{
};

int main()
{
    Bar bar;
    Foo* foo = &bar;
    bool I_WANT_THIS_TO_BE_TRUE = (typeid(*foo) == typeid(Bar));
    return 0;
}
David
  • 171
  • 1
  • 2
  • 7

2 Answers2

7

This fails because you did not declare any virtual functions in Foo. Alter that to have, for example, a virtual destructor, and you will get the hoped-for result.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 1
    Indeed, class is required to have virtual methods to be considered polymorphic (which is required for RTTI to make sense). But a class designed for polymorphism should always provide virtual destructor, so this is not a limitation. – hyde Dec 30 '12 at 14:01
2

What you are looking for is reflection, or RTTI (Run Time Type Information) stuff.

See this for info to get started on subject: Attribute & Reflection libraries for C++?

Unsurprisingly, wikipedia also has article about RTTI: http://en.wikipedia.org/wiki/Run-time_type_information

Then there are frameworks which provide reflection features for objects derived from some common base class (which provides the reflection methods, inherited to all subclasses). An example is Qt's meta object system. These can provide much more information than plain C++ RTTI, and provide full reflection support (such as calling a method by name not known at compile time, for example javascript code calling C++ method).

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176