O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.6. Building an Iterator Class

To illustrate how to overload a set of operators for a class, let’s walk through the implementation of an iterator class. We must support the following usage:

Triangular trian( 1, 8 ); 
Triangular::iterator 
            it = trian.begin(), 
            end_it = trian.end(); 

while ( it != end_it ) 
{ 
    cout << *it << ' '; 
    ++it; 
} 

For this to work, of course, the operators !=, *, and ++ must be defined for objects of the iterator class. How do we do this? We define them as operator member functions. An operator function looks like an ordinary function except that rather than provide the function with a name, we specify the keyword operator followed by the operator we wish to overload. For example,

 class Triangular_iterator { public: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required