pointers - C++ : Polymorphism and operator overloading -
i having troubles figuring out how overload comparison operators have done when using abstract base class. main problem achieve polymorphism using base class, since it's abstract can't instantiated forced use pointer base class in order access derived class methods. i'll put code in order describe situation better :
template <typename _tp> class base { private: _tp attr ; public: foo() = 0 ; friend bool operator == ( base* b1, base* b2) { return ( b1.attr == b2.attr ) ; } }; template <typename _tp> class derived_1 : public base<_tp> { /.../ } ; template <typename _tp> class derived_2 : public base<_tp> { /.../ } ; int main (void) { vector<base*<int> > * v = new vector<base*<int> > (2,0) ; v[0] = new derived_1 () ; v[1] = new derived_2 () ; if ( (*v)[0] == (*v)[1] ) { /.../ } return 0 ; }
so, @ point notice (*v)[0] == (*v)[1]
pointer comparison of base*
. want know if there way overload comparison operator between these 2 pointers, since overloaded operator defined in base class never used.
edit after responses:
since in real code, comparison must (*v)[0] == (*v)[1]
can not compare objects because data structure lose generality. thus, trying ask this:
can comparison of base
pointers done? how?
i'm getting errors compiler telling me :
bool operator == (base*,base*) must have argument of class or enumerated type.
use boost pointer container library
#include <boost/ptr_container/ptr_vector.hpp> ... int main() { boost::ptr_vector<base> v; v.push_back(new derived_1); v.push_back(new derived_2); if (v[0] == v[1]) { std::cout << "success\n"; } }
if want store polymorphic objects in container that uses comparison, boost pointer container library has ptr_set
, ptr_map
, ptr_multiset
, ptr_multimap
. however, mentioned heap. there no boost::ptr_priority_queue
. in case, can provide own comparator std::priority_queue
.
struct baseptrcomp { bool operator()(base const* lhs, base const* rhs) const { return *lhs < *rhs; } }; ... std::priority_queue<base*, std::vector<base*>, baseptrcomp> v;
although recommend use smart pointers here instead.
Comments
Post a Comment