Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top