class MyIterator {
public:
// constructor: argument is associated outer object
MyIterator(OuterObject&);
// next: return a pointer to the next object,
// or a null pointer if no more
InnerObject* next();
// operator form: a synonym for next
InnerObject* operator++(POSTFIX_OP) {return next();}
// reset the iterator to point to the first object
void reset();
}
POSTFIX_OP
is a macro that is defined to be an empty string on older compilers (such as cfront 2.1 and versions of g++ before 2.4) and to the string "int" with newer compilers. This conditional behavior is required because of the evolution of the C++ language; previously, postfix and prefix forms of the operators ++ and - were not distinguished when overloaded; now, a dummy int argument indicates that the postfix form is intended. A typical programming application for iterators might be something like
// print the names of all objects in the container
ListIter nextItem(myList);
Item *itemP;
while ((itemP = nextItem++) != 0)It is, as a rule, not safe to modify most container classes in parallel with the use of an iterator, as the iterator may attempt to access an object that does not exist any more. However, the
cout << itemP->name() << "\back n";
reset
member function will always make the iterator safe to use even if the list has been modified (user-written iterators should preserve this property).