"typeid" counterpart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <typeinfo>
using namespace 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
 
class CDerivedClass *

as an output

Thanks.
But it's more than that.

It only works if CBaseClass has at least one virtual method or virtual destructor.
I tried the last example in that link in VC++ 6.0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// typeid, polymorphic class
#include <iostream>
#include <typeinfo>
#include <exception>
using namespace std;

class CBase { virtual void 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


What may be the issue? Thanks.
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$.
I've tryed it on VC++ 9 and I don't get that warning. If you want you can download it at http://www.microsoft.com/express/download/#webInstall
Last edited on
Got it. We have to enable the RTTI option by including the /GR switch in C++ tab under project->settings
Topic archived. No new replies allowed.