Can a class be attached to itself?

** If the structure can be self-referential. as

struct list { struct list *next; }; 

since there is no difference between class and structure except for the default access specifications. is it possible to write a class ...

 class list { class list *next; }; 

or could there be some other syntax for getting a self-reference class.? if so, how? **

+4
source share
1 answer

Yes, but you can only refer to a pointer or a reference to a class (or structure) yourself

A typical way:

 class list { list* next; } 

If you need two classes to reference each other, you just need to forward the class declaration, for example:

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

If you do not have a complete announcement (just an ad ahead), you can post pointers or links. This is because the compiler always knows the size of the pointer or reference, but does not know the size of the class or structure if it does not have a full declaration.

+12
source

Source: https://habr.com/ru/post/1286518/


All Articles