tags:

views:

74

answers:

2

Let's say I have two classes:

class One {
    Two *somevar = new Two;
    // (...)
};

class Two {
    One *somevar = new One;
    // (...)
}

And it's impossible to compile something like that. How to handle it?

+9  A: 

Since all that you are nesting is a pointer, try:

class Two;

class One {
    Two *somevar = new Two;
    // (...)
};

class Two {
    One *somevar = new One;
    // (...)
}

By forward-declaring class Two, you are giving the compiler enough information to be able to create the pointer inside class One. If you were trying to nest the classes themselves and not just pointers, then there would not be any way to solve the problem.

bta
+1. Also in this kind of pseudo-code, the initialization of someVar need to occur in a cpp file including the appropriate headers so that the full class definition is available (required for operator new).
@stinky472- an excellent point, thanks
bta
@stinky472, @bta, it's possible to do this header-only, but you'd have to have to have the initialization done in the constructor, defined externally from the declaration. The constructor (make sure you mark it inline) for `One` would have to occur after the definition of `Two.
Nathan Ernst
A: 

I think i found a solution:

// class Type instead of Type
// so:
class Two *somevar = new class Two;
matiit