C++ – Can a Class be self-referenced


**If a structure can be a self-referential. like

struct list
     struct list *next;

as there is no difference between class and struct, except the default access specifiers.
then is it possible to write a class…

class list
     class list *next;

or may be is there any different syntax to get a self-referential class.?
if yes then how?**

Best Solution

Yes, but you can only self-reference a pointer or a reference to the class (or struct)

The typical way is just:

class list { list* next; }

If you need two classes to mutually refer to each other, you just need to forward declare the classes, like so:

class list;
class node;

class list { node* first; }
class node { list* parentList; node* next; }

When you don't have the full declaration (just a forward declaration), you can only declare pointers or references. This is because the compiler always knows the size of a pointer or reference, but doesn't know the size of the class or struct unless it has the full declaration.