OOPortal OOPortal

Operator Overloading  «Prev

Overloading Indirect Member Selection - Exercise

Overloading the operator ->

Objective: Overload the -> operator for the vector class so the operator implements an iterator.


The operator -> is overloadable provided it is
  1. a nonstatic member function returning either a pointer to a class object or
  2. an object of a class for which operator-> is defined.

Such an overloaded structure pointer operator is called a smart pointer operator. It usually returns an ordinary pointer after first doing some initial computation. One use of this type of operator is as an iterator function.
The following vector class member function is a form of iterator:

int& vect::iterate(){
   static int i = 0;
   i = i % size;
   return (p[i++]);

It is called an iterator because it returns each element value of a vect in sequence.


Implement an iterator by overloading the -> operator for the following vector class:

class vect {
   vect(int n = 10);
   ~vect() { delete []p; }
   int& element(int i);        //access p[i]
   int  ub() const { return (size - 1); }  //upper bound
   int*  p;
   int   size;

int& vect::element(int i){
 assert (i >= 0 && i < size);
 return p[i];

The function should have the following prototype:
int* vect::operator->() const;

The code for the vector class is available in a file named vector.cpp, which can be found in the compressed course download file available on the Resources age.
Paste your code below and click the Submit button when you are ready to submit this exercise.