Avoid cyclic references caused by C++ includes headers [duplicate]
-
03-07-2021 - |
Frage
I have 3 classes: A, B and C. C is #include
ed by B, and B is #includ
ed 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.
Lösung
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.
Andere Tipps
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.