RTTI only works when there is at least 1 virtual function / is it really?

Hi guys,

I read everywhere that RTTI can only work if you have at least 1 virtual function.

I use this code:

#include <iostream.h>
#include <typeinfo.h>

class X
{
int i;
public:
void f() {i++;}
};

void main()
{
X x1,x2;
if(typeid(x1)==typeid(x2))
cout<<"same!"<<endl;
}

As you can see I'm not using any virtual functions, and still everything works fine! how can it be?

Many thanks.....
[533 byte] By [Salvadoravi] at [2007-11-20 11:49:07]
# 1 Re: RTTI only works when there is at least 1 virtual function / is it really?
Well, RTTI/typeof need the vtable to determine the type of object. Here is an example to play with:

#include <iostream>

class SomeType
{
public:
// try commenting the next line
virtual void test() { }
};

class SomeOtherType : public SomeType { };

int main(int argc, char* argv[])
{
SomeType *a = new SomeOtherType();
SomeOtherType *b = new SomeOtherType();

if (typeid(*a) == typeid(*b))
std::cout << "same type!" << std::endl;

return 0;
}

- petter
wildfrog at 2007-11-9 1:26:17 >
# 2 Re: RTTI only works when there is at least 1 virtual function / is it really?
Hi Peter,
Thank you for your comment.
It only proove my point.

If I use:

#include <iostream.h>
#include <typeinfo.h>

class A
{
public:
// try commenting the next line
virtual void test() { }
};

class B : public A {};

int main(int argc, char* argv[])
{
A *a = new B;
B *b = new B;

if (typeid(*a) == typeid(*b))
cout << "same type!" <<endl;

return 0;
}

I will get a compile warning and my program will crash:

"warning C4541: 'typeid' used on polymorphic type 'class A' with /GR-; unpredictable behavior may result"

The only way I can run it is by removing the code line

virtual void test() { }

Why?
Salvadoravi at 2007-11-9 1:27:17 >
# 3 Re: RTTI only works when there is at least 1 virtual function / is it really?
Well, of course you need to compile your project with RTTI enabled. I assumed you did. Using typeof with RTTI disabled has somewhat limited functionality, but you could typically use it to compare types in a template function/class (where teh type is known at compile-time).

The only way I can run it is by removing the code lineAnd does the type comparison behave as expected?

- petter
wildfrog at 2007-11-9 1:28:18 >
# 4 Re: RTTI only works when there is at least 1 virtual function / is it really?
Cheers!!!
I didn't know I need to enable anything.

How can I enable RTTI?

thanks again!
Salvadoravi at 2007-11-9 1:29:15 >
# 5 Re: RTTI only works when there is at least 1 virtual function / is it really?
Well, you would have if you looked up the warning in the documentation ;)

Open the the projects property page (right-click the project in the solution explorer). Then navigate down to Configuration Properties / C/C++ / Language / Enable Run-time Type Info.

- petter
wildfrog at 2007-11-9 1:30:14 >