#include <iostream>
#include <typeinfo>
usingnamespace std;
class CBaseClass
{
};
class CDerivedClass : public CBaseClass
{
};
int main()
{
CBaseClass *pB = new CDerivedClass();
cout << typeid(pB).name() << endl;
return 0;
}
The output of this example is
class CBaseClass *
But now, pB represents CDerivedClass. Is there any operator like "typeid" to find the current object to which a type points? ie, in this example, to expect
// typeid, polymorphic class
#include <iostream>
#include <typeinfo>
#include <exception>
usingnamespace std;
class CBase { virtualvoid f(){} };
class CDerived : public CBase {};
int main () {
try {
CBase* a = new CBase;
CBase* b = new CDerived;
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
cout << "*a is: " << typeid(*a).name() << '\n';
cout << "*b is: " << typeid(*b).name() << '\n';
} catch (exception& e) { cout << "Exception: " << e.what() << endl; }
return 0;
}
But I do not get the expected output. I got the following warnings
1 2 3 4 5 6 7
Compiling...
Test.cpp
D:\Bharani\Programming\c++\Typeid_example\Test.cpp(16) : warning C4541: 'typeid' used on polymorphic type 'class CBase' with /GR-; unpredictable behavior may result
D:\Bharani\Programming\c++\Typeid_example\Test.cpp(17) : warning C4541: 'typeid' used on polymorphic type 'class CBase' with /GR-; unpredictable behavior may result
Linking...
Typeid_example.exe - 0 error(s), 2 warning(s)
..and I got the following output
1 2 3 4
a is: class CBase *
b is: class CBase *
Exception: Access violation - no RTTI data!
Press any key to continue
I'm pretty sure the issue is that your compiler sucks :(
Unless you have to explicitly turn on RTTI in your compiler. Some compilers turn it off by default and force you to turn it on. You'll have to check your compiler documentation. Unfortunately (or fortunately, depending on how you look at it), I am not an expert in M$.