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?
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<>
.
The disadvantages (for polymorphic types) with custom type identifier are:
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,
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) {}
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With