Skip to main content

Command Palette

Search for a command to run...

🧩 Self-Referential Class in C++ (Beginner-Friendly Blog)

Published
2 min readView as Markdown

📌 Introduction

In C++, some classes need to refer to objects of the same class.
This concept is called a Self-Referential Class.

Self-referential classes are the foundation of dynamic data structures such as:

  • Linked Lists

  • Trees

  • Graphs

  • Stacks and Queues (node-based)


🔹 What Is a Self-Referential Class?

A self-referential class is a class that contains a pointer to an object of its own class type.

In simple words:

A class that refers to itself using a pointer.


🔹 Basic Syntax

class Node {
public:
    int data;
    Node* next;   // Self-referential pointer
};

Here:

  • Node* next can store the address of another Node object

  • This allows objects to be linked together


🔹 Why Pointer Is Mandatory?

This is NOT allowed

class Node {
    int data;
    Node next;   // ❌ Error
};

Why?

  • Node contains another Node

  • That Node again contains another Node

  • Infinite size → compiler error

Pointer works because:

  • Pointer size is fixed (4 or 8 bytes)

  • Compiler knows how much memory to allocate


🔹 Real Example: Singly Linked List Node

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int value) {
        data = value;
        next = NULL;
    }
};

int main() {
    Node* head = new Node(10);
    Node* second = new Node(20);
    Node* third = new Node(30);

    head->next = second;
    second->next = third;

    // Traversal
    Node* temp = head;
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}

Output

10 20 30

🔹 How It Works (Conceptual View)

+------+     +------+     +------+
| 10   | --> | 20   | --> | 30   |
+------+     +------+     +------+

Each object stores:

  • Data

  • Address of the next object of the same class


🔹 Self-Referential Class in C (Comparison)

struct Node {
    int data;
    struct Node* next;
};

Same concept applies in C using struct.


🔹 Where Are Self-Referential Classes Used?

  • Singly Linked List

  • Doubly Linked List

  • Binary Trees

  • Graph Nodes

  • Dynamic memory structures


🔹 Key Characteristics

  • Contains a pointer to the same class type

  • Enables dynamic memory allocation

  • Helps create flexible data structures

  • Memory efficient and scalable

More from this blog

Amit singh's blog

235 posts