1

How do I overload the dereference operator? What would the declaration look like? I'm creating a list class, but I am have trouble with the dereference operator.

Here is my function for overloading the dereference operator

template <typename T>
T List_Iterator<T>::operator *(){
    return current_link->value;
}

This is the data members in my iterator class

private:
      /* Data Members */
    Link<T>* current_link;

This is my link class

protected:
    T value;
jax
  • 728
  • 1
  • 11
  • 31
  • 1
    That looks like the correct syntax to me. Could you explain what problem you're having? – Brian Bi Feb 24 '14 at 06:44
  • Do you get an error? What is not working as you expected? – Dwayne Towell Feb 24 '14 at 06:44
  • 1
    You may want to do that by reference and/or const-reference. Making a copy of T's in your list is bound to cause wtf-isms later on – WhozCraig Feb 24 '14 at 06:45
  • 1
    You might want to return a reference so you can use the iterator to modify the value (e.g. `*it = whatever`). Apart from that, what trouble are you having? – Mike Seymour Feb 24 '14 at 06:45
  • Also covered in one of the *many* operator overloading suggestions [in this question and answer(s)](http://stackoverflow.com/questions/4421706/operator-overloading/4421719#4421719). Look for "Operators for Pointer-like Types", of which your iterator is one. – WhozCraig Feb 24 '14 at 06:51
  • Even if I return by reference, the value it returns is just garbage. I can't get it to return the value of the 'value' variable in the Link class. – jax Feb 24 '14 at 07:18

2 Answers2

8

You should be returning a reference, not a copy:

T& List_Iterator<T>::operator *() { .... }

Otherwise the semantics are confusing: you could not modify the object that you are "de-referencing".

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

You can also return by address. It's easier to write a->b than (*a).b :

T* operator->() {
    return &current_link->value;
}

You will certainly need a const-version of your iterator, that will basically do the same thing as the first one, with the const versions of the "dereferencing" operators.

Kiwi
  • 2,698
  • 16
  • 15