0

I have 3 classes: A, B and C. C is #includeed by B, and B is #included by A. In class C i have defined a handler for a button, and when the button is pushed, C will PostMessage to object A. If i include A in C, i will have a cyclic reference, so what should i do to avoid this cyclic reference?

EDIT: All includes are made in implementation files.

jww
  • 97,681
  • 90
  • 411
  • 885
MRM
  • 561
  • 5
  • 12
  • 29
  • 1
    You haven't specified if you're including all these files in the implementation (.cc, .cpp) or the header (.h). Looks like most answerers are assuming you meant the header file. – i_am_jorf Sep 24 '12 at 15:25

3 Answers3

7

You should use forward declarations. Since C is not the owner of A, I'll assume you have a pointer as a member. So you don't need to include:

class A; //forward declaration
class C
{
    A* a;
};

In the implementation file, you'll include A.h but that's OK. Also, if you can, use forward declarations in A.h and B.h where possible.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Well, my class/object structure looks like this: `A` is in fact a window with a `tab control`, each of it's tabs is a `B` object (which is another `tabcontrol`), and each `B` has a `C` obj for each of his tabs. `C` class has a few buttons, that when i press, sends a message to `A`( each button send a different message). And all of those, are part of a another window, the main one. A `C` object does not have a pointer to `A`, and `A` has an indirect pointer to `C` through `B`. – MRM Sep 25 '12 at 15:54
  • @MRM did you understand what a forward declaration is and tried using it? – Luchian Grigore Sep 25 '12 at 15:56
  • Nice. It's exactly what i needed. Thank you! – MRM Oct 01 '12 at 22:04
1

If class X uses class Y only by pointer, you should use a forward declaration of class Y before declaring class X.

It is a good idea to keep your forward declarations in a separate file. iosfwd is a standard example of this approach

If class X uses class Y in other way, for instance has a member of type Y, then you need a whole definition of class Y and forward declaration won't do.

emesx
  • 12,555
  • 10
  • 58
  • 91
0

If you're referring to a cyclic reference of the same header file, a common convention is to wrap the header in a define so the definitions are only included once, like this MyHeader.h file:

#ifndef MyHeader_h
#define MyHeader_h

// my definitions here

#endif  // MyHeader_h

Also widely supported is the #pragma once directive.

mark
  • 5,269
  • 2
  • 21
  • 34