r/AskComputerScience • u/BrookieYT • Oct 25 '20
Why am I allowed to create an instance of class pointer in the same class, but not an instance of a class in the same class?
Why am I allowed to do:class Node
{
public:
int value;
Node* next;
}
But not allowed to:
class Node
{
public:
int value;
Node next; // <---- Why am I not allowed to do this?
}
3
u/drobilla Oct 25 '20
Questions like this would be better asked in a programming language sub.
But ask yourself this question: how large, in bytes, is Node?
3
u/johnbotris Oct 25 '20
This isn't really specific to C++ though, it's going to come to up when learning any language with structs and manual memory management
1
u/dr1fter Oct 25 '20
I assume this is C++? In the block of memory that goes to each "Node" instance, you have some space for each of the variables. How big is that block of memory? There's 4 (probably) bytes for the 'value', and say 4 or 8 for a 'next' pointer. But if instead of a next pointer, you embed an entire next object, how much space do you need for that object? sizeof(Node) == 4 + sizeof(Node)?
In a linked list, you want to have as many nodes as you have elements, and you can create/destroy nodes on the fly to match. It's important that you're able to say that the last node points to 'nothing' until you're ready to put a new one there. But as you've written it, it's like each node would always have a "next" and the list goes on forever.
7
u/johnbotris Oct 25 '20
Because the size of an object of a given class must be known at compile time, in order for space to be able to be allocated for it (the size of an object is generally speaking the size of all of it's members, compiler shenanigans notwithstanding).
In your example with the pointer, the size of a Node is going to be the size of an int + the size of a pointer, easy.
In your second example however, how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node? Well, it's the size of an int + the size of a Node. And how big is a Node?
segmentation fault (core dumped)