can two classes see each other using C++?

Asj picture Asj · Dec 3, 2009 · Viewed 16.9k times · Source

So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?

Answer

Pavel Minaev picture Pavel Minaev · Dec 3, 2009

Put only member function declarations in header (.h) files, and put member function definitions in implementation (.cpp) files. Then your header files do not need to include each other, and you can include both headers in either implementation file.

For cases when you need to reference the other class in member signatures as well, you can use a forward declaration:

class A;

This lets you use pointer and reference types (A* and A&), though not A itself. It also doesn't let you call members.

Example:

// a.h
struct B; // forward declaration

struct A {
   void foo(B* b); // pointers and references to forward-declared classes are ok
};


// b.h
struct A; // forward declaration

struct B {
   void bar(A& a); // pointers and references to forward-declared classes are ok
};


// a.cpp
#include "a.h"
#include "b.h"

void A::foo(B* b) {
   b->bar(*this); // full declaration of B visible, ok to call members now
}


// b.cpp
#include "a.h"
#include "b.h"

void B::bar(A& a) {
   a.foo(this); // full declaration of A visible, ok to call members now
}