tags:

views:

168

answers:

2

**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?**

+10  A: 

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.

Lou Franco
+1 - nice - but that last sentence should end with 'class definition' (not declaration :)
Faisal Vali
+1 Faisal/Lou. "class X;" is a "full declaration" (of an incomplete type). C doesn't call "struct list { int d; };" a definition, but instead calls it a declaration of a complete type. C++ signifies that by calling it a definition. Nice answer otherwise, of course.
Johannes Schaub - litb
A: 

lou franco is totally right.

be careful though, forward declaration will not work if your class is derived from a base class—at least i didn't figure out a way to do so.

knittl
Forward declarations 'work' whatever classes the declared classes will actually be derived from. A type which is a declared class only (and not a defined class) is an incomplete type, so you cannot refer to its members or bases until a full definition is visible.
Charles Bailey