tags:

views:

160

answers:

1

Defined as: Class.h

#ifndef CLASS_H_
#define CLASS_H_

#include "Class2.h"    
#include <iostream>

struct Struct1{
};

struct Struct2{
};

class Class1 {
};

#endif

Then the other header file, where I use this:

#ifndef CLASS2_H_
#define CLASS2_H_

#include "Class.h"

class Class2 {
    public:
        Class2( Struct1* theStruct, Struct2* theStruct2); //Can't find struct definitions
    private:
};

#endif

These are in the same directory. And it isn't seeing those struct definitions! They look to be in global scope to me. Can someone explain to me why Class2 can't see them? The compiler isn't complaining about not finding the header of Class, so it can't be that.

+3  A: 

What follows is a guess at your complete code. Please post that, then we can help you better.


If by any chance your complete code looks like the following then you should change it

#ifndef CLASS_H_
#define CLASS_H_

#include <iostream>
#include "Class2.h"

struct Struct1{
};

struct Struct2{
};

class Class1 {
};

#endif

Because the CLASS_H_ macro will already be defined, in Class2.h the other header won't be included another time, and then at that time Struct1 and Struct2 would not be known yet. Fix it by using a forward declaration where possible. For example in Class2.h:

#ifndef CLASS2_H_
#define CLASS2_H_

// no need for that file
// #include "Class.h"

// forward-declarations suffice    
struct Struct1;
struct Struct2;

class Class2 {
    public:
        Class2( Struct1 theStruct, Struct2 theStruct2);
    private:
};

#endif

If the other header doesn't need the definition of Class2 either, then use a forward declaration too, there. The definition is not needed for (i.e a declaration suffices)

  • References and Pointers
  • Function parameters in function declarations that aren't definitions

It's needed if you want to access a member, want to get the sizeof or want to defined a function that has a parameter type of Class2, Struct1 etc by-value.

Johannes Schaub - litb
You sir, are psychic. The question is then, if I wanted to store a Class2 in Class, how would I reference it in the header file?
windfinder
you will need to include the header then :) But then, you will have to manage to not need the header from that other header then to break the circle :) If it can't break, you will have to use a pointer and allocate the object in the .cpp file with `new`. Try out `shared_ptr` :)
Johannes Schaub - litb