19.2 Self-Referential Classes
A self-referential class contains a member that points to a class object of the same class type. For example, the definition
class Node {
public:
explicit 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
};
defines a type, Node
. Type Node
has two private
data members—integer member data
and pointer member nextPtr
. Member nextPtr
points to an object of type Node
—an object of the same type as the one being declared here, hence the term self-referential ...
Get C++ How to Program, 10/e now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.