Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!gem.mps.ohio-state.edu!apple!agate!helios.ee.lbl.gov!ux1.lbl.gov!beard
From: beard@ux1.lbl.gov (Patrick C Beard)
Newsgroups: comp.lang.c++
Subject: Re: ********
Keywords: Link list and this
Message-ID: <3863@helios.ee.lbl.gov>
Date: 25 Sep 89 15:59:46 GMT
References: <2046@ifi.uio.no>
Sender: usenet@helios.ee.lbl.gov
Reply-To: beard@ux1.lbl.gov (Patrick C Beard)
Organization: Lawrence Berkeley Laboratory, Berkeley
Lines: 53

In article <2046@ifi.uio.no> torfinna@grim.uio.no (Torfinn Aas) writes:
>
>I want to overload the ++ operator, so that by applying ++ to a node-pointer
>it will move the pointer to the next element in the list.
>
>This is what I did:  
>	void node::operator ++ (){
>		this = next;
>	}
>
>	node* ptr;
>	//... point ptr to list
>	(*ptr)++;
>
>This did not advance the pointer ay all. Why not?

Because "this" is a hidden argument to the function node::operator++()
that is passed by value.  It might be the same pointer as ptr, but in
multiple inheritance cases, or others I'm not aware of it won't be.

It is because "this" is passed by value that you can't alter the original
pointer with your overloaded operator.  However, you can get the desired
behaviour if you overload the "->" operator to point to the node that you
have moved to with the "++" operator.  Finally, an application for smart
pointers!

Here's how you might do this:

class List {
private:
	// private implementation stuff..
	Node* headOList;	// the head.
	Node* currentNode;	// the current node that you move forward with ++.
public:
	ListNode();
   ~ListNode();
	void operator++() { if (currentNode) currentNode = currentNode->next; }
	void operator--() { if (currentNode) currentNode = currentNode->prev; }
	void* operator->() { return currentNode->data; }
	void *data;			// dummy element for "smart pointer" to point to.
};

While I'm not sure it's perfectly correct (and I leave the implementation
of the Node to you), I believe that operators should operate on the list
pointer, and not the Node pointers.  And if at all possible, you shouldn't
give the user of the list any sense of the implementation of the list
at all.


-------------------------------------------------------------------------------
-  Patrick Beard, Macintosh Programmer                        (beard@lbl.gov) -
-  Berkeley Systems, Inc.  "..............Good day!" - Paul Harvey  -
-------------------------------------------------------------------------------