user558126
user558126

Reputation: 1271

Circular references in C++ in different files

If i want a circular reference but in two different files in C++, how would I implement that?

For example

AUnit.h

#inclue <BUnit.h>
class AClass : public TObject
{

   __published
        BClass * B;
};

BUnit.h

#include <AUnit.h>
class BClass : public TObject
{
    __published
        AClass *A;     
};

I can't make it in only one file with forward declarations.

Upvotes: 2

Views: 1042

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272567

I assume you're talking about circular dependencies.

The answer is indeed to use a forward declaration, such as:

AUnit.h

#include <BUnit.h>
class AClass : public TObject
{
   BClass *B;
};

BUnit.h

class AClass;  // Forward declaration

class BClass : public TObject
{
   AClass *A;
};

You could even have a forward declaration in both header files, if you wanted.

Upvotes: 2

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76838

You can use forward declaration in this case too:

// AUnit.h
class BClass;
class AClass : public TObject
{

   __published
        BClass * B;
};

// BUnit.h
#include <AUnit.h>
class BClass : public TObject
{
    __published
        AClass *A;     
};

There is no difference to the scenario if they are both in one file, because #include does nothing but inserting the included file (it is really jut text-replacement). It is exactly the same. After preprocessing of BUnit.h, the above will look like this:

class BClass;

class AClass : public TObject
{

   __published
        BClass * B;
};

class BClass : public TObject
{
    __published
        AClass *A;     
};

Upvotes: 6

Related Questions