Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

how to override ++ operator in this case

Posted on 2007-11-24
Last Modified: 2013-12-14
I'm constructing a class for a double linked list's node. I want to overrid ++ operator such as this code. But I know that this pointer in C++ is cannot be assignet value. Please, someone can suggest an idea for this situation. Thanks a lot

#include <iostream>
using namespace std;
//Basic Doubly Linked List node class. 
class DLLNode
	DLLNode() //Default Constructor
		p_data = 0;    //No data.
		p_next = NULL; //New node always has a NULL next node.
		p_prev = NULL; //New node always has a NULL previous node.
	DLLNode(unsigned int data) //Constructor
		p_data = data; //No data.
		p_next = NULL; //New node always has a NULL next node.
		p_prev = NULL; //New node always has a NULL previous node.
	unsigned int data(void) const //Retreive the data of the node. Constant function.
		return p_data;
	DLLNode* prev(void) const //Retreive the preivous pointer of the node. Constant function.
		return p_prev;
	DLLNode* next(void) const //Retreive the previous pointer of the node. Cosntant function.
		return p_next;
	void setdata(unsigned int data) //Set the data of the node. 
		p_data = data;
	void setprev(DLLNode* prev) //Set the previous pointer of the node.
		p_prev = prev;
	void setnext(DLLNode* next) //Set the next pointer of the node.
		p_next = next;
	unsigned int p_data; //Data stored by the node. protected.
	DLLNode* p_prev;     //Pointer to the next node. protected.
	DLLNode* p_next;     //Pointer to the previous node. protected.
ostream& operator << (ostream& out, DLLNode& node) //Output the data of a node.
	out << node.data() << " "; //Output the data of the node, followed by a space.
	return out;                //Return the output stream.
void operator ++ ()
       this = p_next;

Open in new window

Question by:meoconx

Expert Comment

ID: 20343051
Does this explanation of the increment operators help?


I don't understand how you traverse your list with the DLLNode class. Usually if you want to create a list, you have two separate classes, one for List and one for Node, and then possibly one for ListIterator (in which you implement the ++ and -- operators, to traverse the list).
LVL 29

Accepted Solution

pepr earned 65 total points
ID: 20344251
It is not clear what is the purpose of your ++ operator. I guess that increasing the data value is not the goal. Possibly, you want to add a new list node in front of just after this node.

The operator ++ can have prefix or postfix form (like ++i or i++). The usual interpretation is "increase the original and return the new value" for the prefix form and "return the old value and increase the internal value". For the double linked list the interpretation could be different -- like insert the new node in front of this node for the prefix form, and insert the new node after this node for the postfix form. Anyway, you should return reference to some node (old or new). In both cases, you must create new node (using the new operator for the DLLNode class), bind the p_next and p_prev pointers of the new node to the nodes in front and after the new node. You have to update also the p_next pointer of the previous node and p_prev pointer of the next node.

The operator++() denotes the prefix form, the operator+(int) with dummy int says the compiler that this is the postfix version of the operator.

prefix form -- insert the new node

Author Comment

ID: 20344640
I want to override operator ++ just for change the pointer from the current node to its next node.
tmp++ is the same to tmp = tmp->p_next;
is there any way to use with postfix form?
Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.


Author Comment

ID: 20344645
this is just a problem which my friend asked me to solve.

Assisted Solution

SeanDurkin earned 60 total points
ID: 20344800
When you do something like this:

tmp = tmp->p_next;

You're changing the value of tmp (DLLNode *), so it now points to a new DLLNode object (specifically, whatever old tmp's p_next pointed to). This is different from changing the actual class. You're changing a pointer to a DLLNode object, not the object itself. If you were to implement a ++ operator and do something like:


That would be changing the actual object, which is not what you want. Therefore, if you were to implement some kind of iterator for your list of DLLNodes, you would need a separate class to link them together in a list, and then iterate that list. You can't iterate to the next node of a list inside a node class, because the node class is just a node - it can't see the whole list (like an iterator can).

To help clarify things for you, I've attached sample header file code for implementing a doubly linked list (it was an assignment we had in one of the classes I took). Hope this helps:
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
// forward declaration of List class, so ListElement can make 
// it a friend.  NOTE: If List is a friend of ListElement, that
// means that the List class has access to the private members
// of the ListElement class, but no one else does (besides ListElement
// itself). 
class List;
class ListIterator;
class ListElement {
 friend class List;
 friend class ListIterator;
 ListElement(): next(this), prev(this), isHeader(true) {}
 ListElement(int i): item(i), isHeader(false) {}
 ~ListElement() {}  // default destructor
  int item;
  ListElement *next;    
  ListElement *prev;    
  bool isHeader;
class ListIterator {
 friend class List;
  ListIterator() : currentPtr(NULL) { }
  ListIterator operator++();  // advance iterator to the next list node; return value is iterator *after* advancing
  ListIterator operator--();  // advance iterator to the previous list node; return value is iterator *after* advancing
  ListIterator operator++(int);  // advance iterator to the next list node; return value is iterator *before* advancing
  ListIterator operator--(int);  // advance iterator to the previous list node; return value is iterator *before* advancing
  int operator*(); // return contents pointed to by iterator; print "error"
                   // and terminate program if iterator refers to header node
  ListElement *currentPtr;
class List {
    List();   // creates an empty list
    ~List();  // *must* deallocate the entire list
    List(const List &L);  // copy constructor (*must* be a deep copy)
    List & operator =(List &L);  // *must* (deep) copy list, must avoid memory leak,
                                 // and must handle self-assignment
    // these are functions to set and test the list iterator
    void SetStartList(ListIterator &p) {p.currentPtr = head->next;}
    void SetEndList(ListIterator &p) {p.currentPtr = head->prev;}
    bool IsUndefined(ListIterator p) {return (p.currentPtr == head);}
    bool AtEndList(ListIterator p) {return (p.currentPtr == head);}
    bool AtStartList(ListIterator p) {return (p.currentPtr == head);}
    bool AtFirstNode(ListIterator p) {return (p.currentPtr == head->next);}
    bool AtLastNode(ListIterator p) {return (p.currentPtr == head->prev);}
    // Insert integer at the beginning of the list  
    void Prepend(int it); 
    // Insert integer at the end of the list
    void Append(int it);  
    // Remove first integer from list, return through first parameter.
    // Success is set to true if original list is nonempty, false if empty
    void Pop(int &it, bool &success); 
    // Remove last integer from list, return through first parameter.
    // Success is set to true if original list is nonempty, false if empty
    void Pull(int &it, bool &success); 
    // Get first integer on list, return through first parameter
    // Success is set to true if original list is nonempty, false if empty
    void First(int &it, bool &success);
    // Get last integer on list, return through first parameter
    // Success is set to true if original list is nonempty, false if empty
    void Last(int &it, bool &success);
    // insert integer before list element referred to by p
    void InsertBefore(int it, ListIterator p);
    // insert integer after list element referred to by p
    void InsertAfter(int it, ListIterator p);
    // delete list element referred to by p; print "error"
    // and exit if p refers to the header node
    // p is undefined after this function
    void Delete(ListIterator p);
    // apply function "func" to each element on the list
    void MapFunction(void (*func)(int &));
    // returns true if list empty, false otherwise
    bool IsEmpty();     
    int GetSize() {return listSize;}
    // must print out list elements, one per line
    void Print(); 
    ListElement *head;
    int listSize;

Open in new window


Author Comment

ID: 20345024
thanks for all.

Expert Comment

ID: 20345092
In C++, the prefix ++ function for a class-name is defined with the template:

   class-name operator++();

class-name class-name:: operator++(){
  logic to increment class-name
  return *this;

To define the the postfix ++ function, one uses:
String operator++(int x);

Note that the parameter is not used in the method. It is just a way that one can distinguish prefix increment operators from postfix increment operators.

The definition looks as follows:

class-name class-name:: operator++(int garbage){ // postfix operator, return original value
  class-name Return;
  Return = *this;
  increment class-name
  return Return;

Observe that we copy the object before incrementing it. That way, this value can be defined.

If u define a postfix ++ , you can follow the below code:
DLLNode DLLNode:: operator++(int garbage){
    return *p_next;

However this pointer won't be changed, so if u want to traverse the double linked list, u'd better to use
a point which some like iterator in stl.  
SeanDurkin has offerd the code, u can refer to it.

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Socket Programming (Unix) 8 142
Create a path if not exists 7 89
Online file editor, manager 6 85
Indy 10 not Receiving UDP broadcast 3 22
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question