In what order should classes be declared in C ++?

Let's say I have this C ++ code:

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

The compiler will give an error on line 2 because it cannot find class2, and the same thing if I switched the order of the classes. How to solve this?

+4
source share
3 answers

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

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

Two, you can create a declaration before class definitions. This tells the compiler that this class exists, and you have not defined it yet. In this case, place the class2 before the definition of class1 :

 class class2 ; class class1{ class2 *x; }; class class2{ class1 *x; }; 
+22
source
+3
source

First declare class2:

 class class2; class class1{ class2 *x; }; class class2{ class1 *x; }; 
+2
source

All Articles