Re: rtti
Chameleon wrote:
Hi!
I have derived classes `Angle`, `Azimuth`, `Distance`, `Height` from
base class `Relation`.
I want to put all of these in a `vector<Relation>` but they have
different size, so, I create a `union AnyRelation` and I put all of
derived classes inside this union, and the vector become
`vector<AnyRelation>`.
When I want to check what type the derived class is, I use `typeid`.
Is there a better approach, or I am going right?
Mostly theoretically, I can see a situation where the derived classes have
different alignment from the derived class. Thus, even if the hierarchy only
uses single inheritance, you would have to know the type before accessing the
object in the union (and as you do it to learn the type, you have a
chicken-and-egg issue)..
Another try, is to put every derived class in its own vector:
vector<Azimuth>
vector<Angle>
vector<Distance>
and so on.
and in a `vector<Relation>` I can use references to real objects.
With this approach I can avoid the `typeid` because I can check if
pointer of derived class object belongs to a specific `vector`.
This will work.
And a final question:
Its better to create my own rtti, or to use build-in? (for speed)
My own rtti:
------------
class A {
A() : rtti(0) {}
int rtti;
int getRTTI() { return rtti; }
bool isB() { return rtti == 1; }
virtual ~A() {}
};
class B : public A {
B() { rtti = 1; }
};
If you have virtual destructor anyway, you can save an int by defining a virtual
instead
virtual int getRTTI() const { return <type>; }
Using built-in RTTI would work with less effort (although maybe with same
performance).
Please note I do not comment on your design because I do not know its purpose.
Often, however, the designs directly checking the types are suspects. It's
*usually* better make class objects do things by calling virtual functions than
checking their types and do things with them. Again, not knowing your goal, I
can't say with confidence this will work better in your case but you might want
to give it a look.
HTH,
-Pavel