rtti

May 2, 2011 at 2:06am
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?

Another try, is to put every derived class in its own vector:
1
2
3
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`.


And a final question:
Its better to create my own rtti, or to use build-in? (for speed)
My own rtti:
------------
1
2
3
4
5
6
7
8
9
10
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; }
};
May 2, 2011 at 2:20am
There is a simpler way, just use:

vector<Relation*>

instead - all the pointers are of the same size.

Any other reason you need rtti? In general, the need for rtti is a sign of a design flaw somewhere.
Last edited on May 2, 2011 at 2:21am
May 2, 2011 at 6:00am
And if you opt for your own rtti, make a rtti storage variable specific to each derived class and static const, then overload the getRTTI() method (put the static rtti value inside the method if you only use it there). It will remove 4 bytes per object allocated, and an assignmenet in the constructor for each inheritance level of your Relations.

Also, i'm not sure the isB() method is a good practice. B 'should' not need to know about it's children imo. A better way would be to make the overloaded getRTTI static, and then compare :
1
2
3
4
5
Relation* rel;
.......
if(rel->getRTTI()==B::getRTTI()){
 ...
}

Or even simply to integrate that in bool Relation:: operator ==(Relation&)
Last edited on May 2, 2011 at 6:00am
Topic archived. No new replies allowed.