Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type identifier vs RTTI

is there any advantage of using your own type identifier over RTTI?

e.g.

class A { virtual int mytype() = 0; };
class B : public A { int mytype() {return 1;} };
class C : public A { int mytype() {return 2;} };

Could it be faster? Less overhead? Or should one always use RTTI in such a situation?

like image 911
Cookie Avatar asked May 25 '11 12:05

Cookie


3 Answers

Don't assume that RTTI will have more/less overhead than your solution before testing it.

You should try both solutions and measure the performances to get a reliable answer.

I actually asked myself the same question a few years ago and I ended up adding a member variable to "fasten" the type testing, just like you did. Turned out my code was needlessly cluttered with stupid tests while some dynamic_cast<> would have done the same job (in fact, a better job).

I refactored the code to use dynamic_cast<> since then and I wouldn't go back.

As a foot-note: if your classes are polymorphic, you already "paid" for this anyway, so just go with dynamic_cast<>.

like image 171
ereOn Avatar answered Oct 04 '22 02:10

ereOn


The disadvantages (for polymorphic types) with custom type identifier are:

  1. One needs to keep record of every class inherited. You need to assign a unique integer or enum value for all the classes in a given hierarchy
  2. Say your vertical inheritance is like, A->B->D. For situations like, A *p = new D; the custom type identification will not allow to match B* with p (even though it's valid).

You need to be aware of these situations. On the other had,

  1. RTTI is applicable to only polymorphic types (so the inheritance chain not containing virtual functions cannot leverage RTTI)
  2. There is a little performance difference decrease due to RTTI, if it really matters to you

But, as you mentioned in your comment, for smaller inheritance chain, there is no harm in keeping track of your own typing. e.g.

struct Base {
  enum TYPES { _BASE, _D1, _D2, _D3 };
  const TYPES &myType;
  Base (TYPES) : myType(_BASE) {}
};

struct D1 : Base {
  D1 () : Base(_D1) {}
};
like image 25
iammilind Avatar answered Oct 04 '22 00:10

iammilind


http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI

There are some limitations to RTTI. First, RTTI can only be used with polymorphic types. That means that your classes must have at least one virtual function, either directly or through inheritance. Second, because of the additional information required to store types some compilers require a special switch to enable RTTI.

So, if you need it to work on classes without virtual functions, you'd have to implement it yourself.

like image 39
Lou Franco Avatar answered Oct 04 '22 01:10

Lou Franco