tags:

views:

143

answers:

3

Say I got this C++ code:

class class1{
    class2 *x;
}

class class2{
    class1 *x;
}

The compiler would give an error in line 2 because it couldn't find class2, and the same if i switched the order of the classes. How do I solve this?

+2  A: 

Declare class2 first:

class class2;
class class1{
    class2 *x;
};

class class2{
    class1 *x;
};
John Millikin
+19  A: 

Two things - one, you need semicolons after class declarations:

class class1{
    class2 *x;
};

class class2{
    class1 *x;
};

Two, you can create a declaration in front of the definitions of the classes. That tells the compiler that this class exists, and you have yet to define it. In this case, put a class2 declaration in front of the definition of class1:

class class2 ;

class class1{
    class2 *x;
};

class class2{
    class1 *x;
};
swongu
+3  A: 

Refer Forward declarations

aJ