Nerfi
Nerfi

Reputation: 93

How to declare a pointer within a class definition to the class being defined?

I am new to C++, and I am learning classes now. I have found this class and wondering how works object created as a pointer in its own class. Can you guys explain it please? Where and how can it be used?

class Car {
public:
    int weight;
    const char* model;
    Car* other;
};

Upvotes: 0

Views: 374

Answers (2)

ruohola
ruohola

Reputation: 24107

This can be used for example in a linked-list where a Node of the list has to also hold a reference to the next Node in the list.

class Node
{
public:
    int value;
    Node* next;
};

class LinkedList
{
public:
    Node head;
}

The reason why the next Node is a pointer here is that the class is not yet fully defined and thus the compiler doesn't know its size. But since pointers have always a fixed size, we can store a Node* as a class member just fine.

Upvotes: 4

jfMR
jfMR

Reputation: 24788

class Car {
public:
    // ...
    Car* other;
};

At the moment of declaring the data member other, the Car class is actually an incomplete type (i.e., it is not completely defined). As a result, the compiler doesn't know the size of a Car object yet. However, since this data member other is a pointer to a Car object rather than a Car object, the compiler does know the size of other.

Upvotes: 3

Related Questions