Reputation: 181
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;
}
Upvotes: 2
Views: 129
Reputation: 62898
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).
Upvotes: 2
Reputation: 147018
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.
Upvotes: 7