Well, at the time you put that member, the nesting class, myclass, is not complete yet. You can define the mystruct type afterwards, when myclass is complete:
class myclass {
struct mystruct;
};
struct myclass::mystruct {
myclass something;
int something_else;
};
Note that just because mystruct is a nested type of myclass, that does not mean that myclass contains an object of mystruct. So there is no problem with circular containment here. Since you mention you come from Java - maybe it helps you when i tell you nested classes are like static nested classes in Java. In fact, C++ does not have "non-static nested classes" like they exist in Java. So if you create a myclass object, neither there is a mystruct object automatically created and embedded, nor there is a special relationship between a mystruct that can be created and any created object of the nesting class. What nested classes in C++ buy you (probably some more - this is from the top of my head):
- Including members of the outer class into usual unqualified name-lookup (1)
- Automatic friendship of the nested class and the nesting class - the nested class can access non-public members of the nesting class. (2)
- Hiding or encapsulating the nested class from outside into the nesting class.
Here is an example:
class myclass {
typedef int test_type;
struct mystruct;
mystruct * s;
};
struct myclass::mystruct {
mystruct() {
// note, setting private member (2)
something.s = this;
// note, we don't have to type myclass::test_type (1)
test_type silly_integer = 42;
}
myclass something;
int something_else;
};
But you probably meant to put a pointer to the nesting class anyway in your code - which is often needed when nested classes are into the game. You have to remember that when you have a variable, that variable is the name for the object itself - instead of merely a reference (like in java) to it. A C++ pointer, however, behaves like a Java reference - it can be nulled and point to different objects during its lifetime:
struct myclass::mystruct {
myclass *something;
int something_else;
};
That will make it merely reference an object of type myclass, which is to be created elsewhere, instead of being that object itself. So, it is like a node that may have one parent (pointed to by something) - but doesn't have to. And like an iterator that points to some container it's iterating over.
There is also the other way around, where the nesting class has a pointer to the nested class (apart from my silly example above). That's very commonly used in the pimpl idiom. I highly recommend you to have a look at it.