Typeinfo is bound statically when a class doesn't have any virtual functions - the compiler works out which typeinfo to use at compile time. If you have one virtual function then the type_info is looked up at runtime from the v_table. If you define base the way you do in the third answer or CPalini did in the second you'll not end up with the correct type_info for a class. Bung on one virtual function and all will be well.
To illustrate this:
#include <typeinfo>
#include <string>
template<typename T>
std::string type_name_string( const T *p )
{
return typeid( *p ).name();
}
class A
{
};
class B: public A
{
};
int main()
try
{
B b;
std::cout << type_name_string( static_cast<const A *>( &b ) ) << std::endl;
}
catch( std::exception &e )
{
std::cout << "Something went wrong: " << e.what() << std::endl;
}
catch( ... )
{
std::cout << "Something went wrong, no idea what!" << std::endl;
}
On VC++ 2010 this always prints "class A."
Now add a virtual function to A...
#include <typeinfo>
#include <string>
template<typename T>
std::string type_name_string( const T *p )
{
return typeid( *p ).name();
}
class A
{
public:
virtual ~A(){}
};
class B: public A
{
};
int main()
try
{
B b;
std::cout << type_name_string( static_cast<const A *>( &b ) ) << std::endl;
}
catch( std::exception &e )
{
std::cout << "Something went wrong: " << e.what() << std::endl;
}
catch( ... )
{
std::cout << "Something went wrong, no idea what!" << std::endl;
}
Which now always prints "class B."
Personally I'd not bother making type introspection a member of a class - about the only thing making it a class member does is guarentee that you have a virtual function in the base class, which may or may not be what you want. Not all classes need virtual functions so I'd be a bit loathe to stick them in where they're not needed.
Cheers,
Ash
PS: Buy a copy of the "C++ Programming Language" by Stroustrup. He goes over how to use typeid and type_info including the requirement for at least one virtual function. For more "why it works that way in C++" have a gawp at "The Design and Evolution of C++" by the same author.