Self-Referential Classes

A self-referential class contains a pointer member that points to a class object of the same class type. For example, the definition

class Node { public: Node( int ); // constructor void setData( int ); // set data member int getData() const; // get data member void setNextPtr( Node * ); // set pointer to next Node Node *getNextPtr() const; // get pointer to next Node private: int data; // data stored in this Node Node *nextPtr; // pointer to another object of same type }; // end class Node

defines a type, Node. Type Node has two private data membersinteger member data and pointer member nextPtr. Member nextPtr points to an object of type Nodeanother object of the same type as the one being declared here, hence the term "self-referential class." Member nextPtr is referred to as a linki.e., nextPtr can "tie" an object of type Node to another object of the same type. Type Node also has five member functionsa constructor that receives an integer to initialize member data, a setData function to set the value of member data, a getdata function to return the value of member data, a setNextPtr function to set the value of member nextPtr and a getNextPtr function to return the value of member nextPtr.

Self-referential class objects can be linked together to form useful data structures such as lists, queues, stacks and trees. Figure 21.1 illustrates two self-referential class objects linked together to form a list. Note that a slashrepresenting a null (0) pointeris placed in the link member of the second self-referential class object to indicate that the link does not point to another object. The slash is only for illustration purposes; it does not correspond to the backslash character in C++. A null pointer normally indicates the end of a data structure just as the null character ('') indicates the end of a string.

Figure 21.1. Two self-referential class objects linked together.


Common Programming Error 21.1

Not setting the link in the last node of a linked data structure to null (0) is a (possibly fatal) logic error.

Категории