1

I am stumped by what seems to be a strange issue with assigning a value to a type. This is the code giving me issues:

1. ListIterator<int> itr = lst.begin();
2.itr++;
3.itr = lst.begin();

So line 1 and 2 work fine; however, when I try making itr = lst.begin() after it has been declared I get the following error:

ListMain.cpp:46: error: no match for ‘operator=’ in ‘itr = lst. List<T>::begin [with T =      int]()’
List.h:183: note: candidates are: void ListIterator<T>::operator=(ListIterator<T>&)   [with T = int]

Now my operator= is currently this:

void operator = (iterator & rhs) {theList = rhs.theList; currentLink = rhs.currentLink;}

So since my begin() function returns a ListIterator shouldn't this just reassign the list iterator or am I missing something?

Any insight to this problem would be greatly appreciated.

1 Answers1

2

Your operator= takes its argument by non-const reference. As such, temporaries (such as the object returned by begin()) cannot bind to it. If you need a custom copy assignment operator, change it like this:

void operator = (const iterator & rhs) {theList = rhs.theList; currentLink = rhs.currentLink;}

In addition, to make the operator conform to the standard library requirements, you should change it to return a reference to the object being assigned to:

iterator& operator = (const iterator & rhs) {
  theList = rhs.theList;
  currentLink = rhs.currentLink;
  return *this;
}

Lastly, do you need a custom assignment operator at all? What yours does is just assignment of members. If they are all members, you're better off removing the operator entirely and relying on the compiler-generated one.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • So what your saying is that by adding a the const I make it so that a function like begin() can bind to it? –  Oct 16 '13 at 07:14
  • Sorry I am barely in data structures and the professor told us that this was the way to declare this and yes I need the to make custom operators. Actually I learned more from your explanation than in lab or lecture. –  Oct 16 '13 at 07:18
  • @user2881196 In C++, a "real" object (one which has a name or was allocated dynamically) is called an l-value and it can bind to both const-references `const T&` and non-const references `T&`. A temporary object (such as returned from a function by value) is called an r-value and can only bind to const-references `const T&` (and in C++11, to r-value references `T&&`). For more info, see [this question](http://stackoverflow.com/q/19375634/1782465) and the one linked from comments there. – Angew is no longer proud of SO Oct 16 '13 at 07:29