Angelwings said:
Hi everyone,
I've to write my own definition of a BST with polymorphic data, as an
university course project.
I have troubles about comparing data when it's defined as polymorphic
pointer.
In my situation I've something like:
class A {}
class B : public A {}
class C : public A {}
and a BST allocated as bst<A*>
Since we have no idea what the bst<> template looks like, the last piece of
information is by and large useless.
how should I discern when i've to compare pointers (as the example) or
objects (as bst<B> for example)?
Huh? How would a bst<B> come up if you have a bst<A*>?
Anyway, here is a suggestion on how to separate concerns: first implement a
basic_bst<T> template that does not support polymorphism at all. Instead it
presupposes the existence of a binary predicate
bool less_than ( T lhs, T rhs )
or
bool less_than ( T const & lhs, T const & rhs )
and does all comparison through that predicate. (Of course, you would be
reinventing the wheel at this point, since the associative standard
containers implement exactly this.)
Then, define a forwarding comparison predicate:
bool less_than ( A const * lhs, A const * rhs ) {
assert ( lhs != 0 );
assert ( rhs != 0 );
return ( polymorphic_less( *lhs, *rhs ) );
}
And finally define
bool polymorphic_less ( A const & lhs, A const & rhs )
in a way appropriate for comparing objects of types derived from A. Note
that the const-reference parameters preserve the dynamic type.
Now, you can use basic_bst<A*> to store non-null A* which will be compared
through comparison of pointees. Finally, you can write your polymophic
bst<A> as a wrapper around basic_bst<A*> essentially changing the interface
from using non-null A* to A&.
Note: There is one major issue that you will have to deal with, namely
whether objects shall be copied into the search tree or whether the search
tree just holds pointers to the original objects (this ought to be
mentioned somewhere in the specs). In the first case, you would need to
clone the objects as you populate the tree and you would need to dispose of
them when they are removed.
Best
Kai-Uwe Bux