Multi-File Woes

I want two classes defined in two files to have members of each other however my compiler isn't letting me do so.

main.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef MAIN_H
#define MAIN_H

#include "main2.h"

class Class1
{
  Class2 *m_class2;
  public:
    Class1();
};

#endif 


main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "main.h"

Class1::Class1()
{

}

int main(int argc, char *argv[])
{
  return 0;
}


main2.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef MAIN2_H
#define MAIN2_H

#include "main.h"

class Class2
{
  Class1 *m_class1;
  public:
    Class2();
};

#endif 


main2.cpp
1
2
3
4
5
6
#include "main2.h"

Class2::Class2()
{

}


Fairly straightforward example, main.cpp/h declares the first class and includes main(), main2.cpp/h declares the second class. The first class is supposed to have a member that's a pointer to the second class, and the second class is supposed to have a member that's a pointer to the first class. The compiler error I get is:

(line 8 of main.h) ISO C++ forbids declaration of `Class2' with no type

Is there some way to remedy my problem?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
using namespace std;

class Class2; //forward declaration

class Class1
{
public:

    Class2 * m_class2;
};

class Class2
{
public:

    Class1 * m_class1;
};

string truth_table[]= {"false","true"};

int main()
{
    Class1 c1;
    Class2 c2;

    c1.m_class2=&c2;
    c2.m_class1=&c1;

    cout << truth_table[(&c1==c1.m_class2->m_class1)] << endl;
    cout << truth_table[(&c2==c2.m_class1->m_class2)] << endl;

    cout << "hit enter to quit..." << endl;
    cin.get();
};
Last edited on
For my case I need them in separate files.
Instead of including the header file of the class you want, only forward declare if you are using a pointer.
@Zhuge: does not work.

main.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef MAIN_H
#define MAIN_H

class Class2;

class Class1
{
  public:
    Class1();
    Class2 *m_class2;
};

#endif 


main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "main.h"

Class1::Class1()
{

}

int main(int argc, char *argv[])
{
  Class1 hi;
  hi.m_class2->m_member2 = 5;
  return 0;
}


main2.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef MAIN2_H
#define MAIN2_H

class Class1;

class Class2
{
  Class1 *m_class1;
  public:
    Class2();
    int m_member2;
};

#endif 


main2.cpp
1
2
3
4
5
6
#include "main2.h"

Class2::Class2()
{

}


Error:
main.cpp|11|error: invalid use of undefined type `struct Class2'|
Last edited on
#include "main2.h" in main.cpp
+1 m4ster r0shi

Both .cpp files should be including both headers.

But the headers should not be including each other.

Obligatory link: http://cplusplus.com/forum/articles/10627/
Topic archived. No new replies allowed.