Overloading the ++ operator to incriement an iterator

Feb 21, 2012 at 10:05pm
Hello,

I am currently creating a sqaure list and one of the requrements is to overload the the pre and post ++ operator.

Ive tried overloaded the ++operator in my .hpp file to increment an interator. But when calling the ++operator it does not call the overloaded code and just uses the default.

1
2
3
4
5
6
7
8
9
10
11
12

iterator& operator ++ () {  // pre-increment 
        std::list<int>::iterator i = list_Values.begin(); 
        advance(i,1); 
        return &*i; 
    } 
 
    iterator operator ++ (int) { // post-increment 
        std::list<int>::iterator i = list_Values.begin(); 
        advance(i,1); 
        return &*i; 
    } 
Last edited on Feb 21, 2012 at 10:13pm
Feb 21, 2012 at 10:07pm
What do you mean the default? There is no default...

Also the point of the post-xxx operator is that it makes a copy, does something to the original, then returns the copy.
Feb 21, 2012 at 10:10pm
Well when I say default,I mean that it seems to do the ++ operator in the standard library instead of what I created.

I'm not sure if my code is 100% right but I hope i'm close.
Last edited on Feb 21, 2012 at 10:11pm
Feb 21, 2012 at 10:11pm
There is no such type name as iter in std::list class.
Feb 21, 2012 at 10:14pm
@vlad from moscow - see changes
Feb 21, 2012 at 10:25pm
Well looking at your code I can conclude that the same iterator is always used after incrrement

1
2
3
4
5
iterator& operator ++ () {  // pre-increment 
        std::list<int>::iterator i = list_Values.begin(); 
        advance(i,1); 
        return &*i; 
    } 


I.e. you always return begin() + 1. However I think you should get begin() + 1 after the first increment then begin() + 2 after the second increment and so on.
Feb 21, 2012 at 10:50pm
@vlad from moscow

I tried this and when i try to incirment an iterator it doesnt get called.

All i did was

int* test;

test = sqrlst.begin();
++test;

Thank you for the suggestion..if you have any more please let me know
Last edited on Feb 21, 2012 at 10:50pm
Topic archived. No new replies allowed.