0

I have something similar to the following:

header1.h

#include "header2.h"

struct MyStruct
{
    int aVariable;
};

class AClass
{
    AnotherClass m_anotherClass;
}

header2.h

class AnotherClass
{
   AnotherClass(MyStruct & myStruct)
      : m_myStruct(myStruct)
   {

   }
   MyStruct & m_myStruct;
};

I was wondering how I can get access to MyStruct in header2.h when I have defined it in header1.h. I know I could just move definition of the struct into header2.h but it wouldn't really make sense for it was meant for.

The only reason I wanted to do it this way was because I wanted to be able to get to the data stored in aVariable that gets updated in header1.cpp.

Kev
  • 11
  • 1
  • 4
  • 1
    [Google forward declaration C++](https://www.google.com/search?q=forward+declaration+C%2B%2B&oq=forward+declaration+C%2B%2B&aqs=chrome..69i57j0l5.327j0j7&sourceid=chrome&es_sm=93&ie=UTF-8) – crashmstr Oct 12 '15 at 18:10

3 Answers3

3

You need to add a forward declaration in header2.h.

// Forward declare MyStruct
struct MyStruct;

class AnotherClass
{
   AnotherClass(MyStruct & myStruct)
      : m_myStruct(myStruct)
   {

   }
   MyStruct & m_myStruct;
};
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks! So I fixed that and another problem arose with it. I'm trying to now use aVariable in a function from AnotherClass but the compiler is complaining about " use of undefined type 'MyStruct' ". Any sugestions? – Kev Oct 12 '15 at 18:31
  • You cannot use access member variables or functions of a struct that is just forward declared. You'll need to move the implementation of the function to a .cpp file. In the .cpp file, you'll need to include "header1.h". – R Sahu Oct 12 '15 at 18:34
  • Exactly what I was looking for, thanks! – Kev Oct 12 '15 at 18:38
0

You could just move the struct definition into header2.h, assuming you include header1.h into header1.cpp. Then, since header1.cpp includes header1.h, which in turn includes header2.h, header1.cpp will also have access to the structs and classes defined in header2.h.

BurningLights
  • 2,387
  • 1
  • 15
  • 22
0

You can use a forward declaration for struct MyStruct. Since you are using a reference, you don't need to include header1.h. You won't be able to define function inline in this header if they use the struct however since you need its definition for that.

Eric Fortin
  • 7,533
  • 2
  • 25
  • 33