Question has been modified
I have a list class (like linking list) that contain add() and begin() functions
add() function that adds to tail
begin() function that returns the address of the first element (head)
i try to make my class support for-range for(:) so i try to implementation begin(), end() and operator++() functions, But I got stuck on operator++() it doesn't work (read the note below)
New Addition
the problem is that the i is a Node Pointer so I can't do this ++i that will just increase the address of the pointer and it will not run the operator++() because it is a Node Pointer not an Object from Node struct so when i do this ++(*i) it will run the operator++()
#include <iostream>
using namespace std;
class List
{
struct Node
{
int info;
Node *next;
Node(int val) : info(val), next(NULL) {}
Node * operator++(){ // not working
cout << "i am alive\n";
*this = *this->next;
return this;
}
};
Node *head = NULL;
Node *tail = NULL;
public:
void add(int val) // add to tail, O(1)
{
Node *temp = new Node(val);
if (!head)
{
head = temp;
tail = temp;
return;
}
tail->next = temp;
tail = temp;
}
Node *begin()
{
return head;
}
};
int main()
{
List l;
l.add(2);
l.add(5);
l.add(10);
auto i = l.begin(); // *i is 2
++i;
cout << (*i).info; // output is 0
}
NOTE THAT: if i do that, it will work and print 5
auto i = l.begin(); // *i is 2
i->operator++(); // will work
// ++(*i); //also will work
cout << (*i).info; // output is 5