Self-Referencing Classes • Dynamic Memory • Garbage Collection
1. SELF-REFERENCING CLASSES
1.1 Introduction
A Self-Referencing Class is a class that contains a pointer to an object of the same class type.
This concept is extremely important in data structures, especially in:
• Linked Lists
• Trees
• Graphs
In simple words:
Ek class jo apnay hi type ke object ka address store kare.
1.2 Basic Concept
Instead of storing data only, a self-referencing class also stores a link (pointer) to another object.
General Structure
class Node {
public:
int data;
Node* next; // Self-reference pointer
};
Yahan Node* next ka matlab hai ke yeh pointer kisi doosray Node ko point karega.
1.3 Memory Representation
Each object contains:
• Data part
• Address of next object
Example:
[10 | address] → [20 | address] → [30 | NULL]
1.4 Example: Singly Linked List Node
Question Statement
Write a C++ program to create a simple linked list using self-referencing class.
, Program
#include <iostream> // Input/Output library
using namespace std;
// Self-referencing class
class Node {
public:
int data; // Har node ka data store karega
Node* next; // Pointer jo next node ka address store karega
// Constructor
Node(int value) {
data = value; // Jo value pass hogi wo data me store hogi
next = NULL; // Initially next NULL hoga (koi next node nahi)
}
};
int main() {
// Step 1: Nodes dynamically create karna (heap memory me)
Node* head = new Node(10); // First node (head) with value 10
Node* second = new Node(20); // Second node with value 20
Node* third = new Node(30); // Third node with value 30
// Step 2: Nodes ko link karna (chain banana)
head->next = second; // Head node ka next, second ko point karega
second->next = third; // Second ka next, third ko point karega
third->next = NULL; // Last node ka next NULL (end of list)
// Step 3: Traversing (list ko print karna)
Node* temp = head; // Temporary pointer head se start karega
while (temp != NULL) { // Jab tak temp NULL na ho
cout << temp->data << " -> "; // Current node ka data print
temp = temp->next; // Next node par move karo
}
cout << "NULL"; // End of linked list show karne ke liye
return 0; // Program successfully end
}
Explanation (Line by Line)
• Node* next; → pointer to next node
• new Node(10) → dynamic memory allocation
• head->next = second; → linking nodes
• Loop → traversal
1.5 Applications
Self-referencing classes are used in:
• Linked Lists
• Binary Trees
• Graph adjacency lists