Hey guys, im having some trouble in finding what I should return with the [] operator overloading. Here is my implementation code:

template <typename L>
    L& List<L>::operator[](int index) throw (ListException)
    {
       if (index >= length || index < 0)
       {
          throw ("In function: operator[]: index >= length or < 0");
       }
       else
       {
          Node<L>* ptr = first;
          ptr->next = first->next;
          int cnt=0;
          while (cnt < index)
          {
             ptr = ptr->next;
             cnt++;
          }
       }   
       return *ptr->data;
    }

I keep getting the error: 'ptr' was not declared in this scope
It gives me this error at the line

return *ptr->data;

I cant figure out what return value I need to use. I know it shouold be L&, which is a dereferenced value of one module of that list...but im having trouble. Ive tried simply ptr->data, among many other things. Any help would be greatly appreciated! Thanks! =)

Declare Node<L>* ptr; inside your method but outside the else block. Then inside of else set *ptr = first; You might need to change what you return but I'm not absolutely sure.

commented: Solved my problem =) +1

that worked! inside the else block i had to set ptr=first; instead of *ptr=first;

and my return had to be
return ptr->data;

Thank you so much!
may I ask why i could declare it while setting it equal to first? thanks so much for your help =)

that worked! inside the else block i had to set ptr=first; instead of *ptr=first;

Sorry about that. I was going to compile an example to make sure I told you that correctly and I got side tracked.

Anytime you have a set of braces a new scope is set up, meaning (among other things) that anything that is declared on the inside is not visible outside. But anything visible outside is visible inside, so you could have initialized your variable outside of the else statement. I was just trying to help you keep your code together. The thing about the braces is, once you close that scope, anything declared inside disappears (just like with functions and local variables). So you were trying to return something that no longer existed.

Ok, great! thanks, that makes a lot of sense! youve been a big help, thanks again!

No problem at all!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.