scg_ wrote:
template <class T>
class A {
public: virtual int size() const = 0;
class iterator;
friend class iterator;
class iterator {
public:
virtual T& operator*() const = 0;
virtual T* operator++() = 0;
};
virtual iterator begin() const = 0; // error
};
This interface is broken in at least two ways. First, operator++ should
not return a T*, but an iterator reference (return *this after
incrementing). Second, you can't use polymorphism with static objects.
If you want iterator to be polymorphic, and the begin() function to be
able to return a sub, then you need to use heap allocation and the begin
function needs to return a pointer, reference, or some smart object that
can encapsulate the heap allocation (shared_ptr, auto_ptr, etc).
Otherwise, even if you do adjust begin() to return an iterator you'll
run into slicing and what the client gets will be an A<>::iterator, not
a subclass (in this case that just plain won't compile since iterator is
abstract).
Yes, this is exactly what I am observing. I was not aware of the term
Quite frankly, I doubt you need to do this. The strength of STL objects
is their use of compile time polymorphism. Trying to override that
seems to be a lot of work with little benefit. I've never needed to do
it. Doesn't mean you don't...just that you may not be looking at all
available solutions.
Thank you very much. Your comments have been exceedingly revealing.