-1

Say I have these two classes:

// a.h

#include "b.h"

and:

// b.h

include "a.h"

I understand there is a problem over here, but how can I fix it and use a objects and their methods in b class and vice versa?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Itzik984
  • 15,968
  • 28
  • 69
  • 107

4 Answers4

2

You can use forward declarations, like this:

class B;

class A
{
    B* ThisIsValid;
}

class B
{
    A SoIsThis;
}

For more information, see this SO question.

As for the preprocessor #includes, there's likely a better way to organize your code. Without the full story, though, it's hard to say.

Community
  • 1
  • 1
Maxpm
  • 24,113
  • 33
  • 111
  • 170
1

To extend on @Borealid 's answer:

To avoid problems with circular includes, using an "include guard"

eg.

#ifndef MYFILE_H /* If this is not defined yet, it must be the first time
 we include this file */
#define MYFILE_H // Mark this file as already included
// This only works if the symbol we are defining is unique.

// code goes here

#endif 
Tim
  • 834
  • 2
  • 12
  • 31
0

You can use what is called a "forward declaration".

For a function, this would be something like void myFunction(int);. For a variable, it might look like extern int myVariable;. For a class, class MyClass;. These bodiless statements can be included before the actual code-bearing declarations, and provide the compiler with enough information to produce code making use of the declared types.

To avoid problems with circular includes, using an "include guard" - an #ifdef at the top of each header file which prevents it being included twice.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • This answer doesn't discuss the real core of the thing, which is that you restrict your mention of `B` in `A`'s header to forward declarable things, but in `A`'s source file you are free to `#include` the full definition because nothing is going to `#include` the source file... you're not going to have any circular dependencies with it. This _only_ affects headers, and that's how we can make use of an approach that effectively cripples use of a type. – Lightness Races in Orbit Sep 10 '11 at 22:37
0

The "other" class can only have a reference or pointer to the "first" class.

in file a.h:

#include "b.h"

struct a {
    b m_b;
};

in file b.h:

struct a;

struct b {
    a* m_a;
};

void using_the_a_instance(b& theb);

in file b.cpp:

#include "b.h"
#include "a.h"

void using_the_a_instance(b& theb)
{
    theb.m_a = new a();
}
Johann Gerell
  • 24,991
  • 10
  • 72
  • 122