Can you define two classes on the same source file?

I have an issue with a program I am creating that wants to use one object as a parameter. When I had first wrote the program, I ended up with huge errors regarding cyclic dependency, but now I don't know what the syntax would be to define two classes on a single source file. I need an implementation file as well, which is generally where errors get generated like class not defined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef //ifndef what?  class1,class2?  
#define //define what?  


class CLASS1
{
    void useOtherClass(class2 object1);
};

class CLASS2
{
    void useOtherClass(class1 object2);
};

#endif 



Edit, additionally, if I must stick to multiple header files, what is causing classes to be undeclared here?

1
2
3
4
5
6
7
8
9
10
11
12
#ifndef CLASS1_H
#define CLASS1_H

#include"CLASS2.h"

class CLASS1
{
    void useOtherClass(CLASS2 object1);
};


#endif 



1
2
3
4
5
6
7
8
9
10
11
12
13

#ifndef CLASS2_H
#define CLASS2_H

#include"CLASS1.h"

class CLASS2
{
    void useOtherClass(CLASS1 object2);
};


#endif 
Last edited on
look up an example of 'forward declaration'

You just need a forward declaration for each class:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef CLASS1_H
#define CLASS1_H

#include"CLASS2.h"
class CLASS2;

class CLASS1
{
    void useOtherClass(CLASS2 object1);
};


#endif  

And

1
2
3
4
5
6
7
8
9
10
11
12
#ifndef CLASS2_H
#define CLASS2_H

#include"CLASS1.h"
class CLASS1;

class CLASS2
{
    void useOtherClass(CLASS1 object2);
};

#endif  
Topic archived. No new replies allowed.