How to overload the indirection operator? (C++)

user98188 picture user98188 · May 21, 2009 · Viewed 9k times · Source

I'm trying to create an iterator class as a member-class for a list class, and am trying to overload the indirection operator (*) to access the list it's pointing to:

template<class T>
T list<T>::iterator::operator*(iterator& iter)
{
    return ((iter.lstptr)->current)->data;
}

where lstptr is a pointer to a list, current is a pointer to a node class, and the node class contains the data member data of type T.

Iterator is declared like this:

template<class T>
class list
{
public:
class iterator;
};

template<class T>
class list<T>::iterator
{
//stuff
};

I am able to compile the function definition of the overloaded operator* fine, but when I try to do something like:

list<int> lst1;
lst1.add(6);
list<int>::iterator IT;
IT = lst1;
//everything above this point compiles fine
int a = *IT; //error here (line fourteen)

The error I get says <1> that I am using an illegal indirection, and <2> that it cannot convert from list::iterator to int. Both errors occur on line fourteen.

Does anybody know what I am doing wrong and how I can overload the indirection operator correctly?

NB: If you need to see more code, tell me which part, because I don't want to put th entire code up here because it's abot 205 lines, and 204 of those lines don't (I think) have any errors.

Answer

Drew Dormann picture Drew Dormann · May 21, 2009

You overloaded the multiply operator. Take the parameter out to make it an indirection operator.

template<class T>
T list<T>::iterator::operator*()
{
    return ((this->lstptr)->current)->data;
}

You should also have it return a reference if you want code like *IT = 3; to compile.

template<class T>
T& list<T>::iterator::operator*()
{
    return ((this->lstptr)->current)->data;
}