CodeRider
CodeRider

Reputation: 1814

Cyclic dependency for classes inside different namespaces C++

I have two classes:

Class A and Class B

Class A is declared under namespace Common::subnamespace1

Class B is declared under namespace Common::subnamespace2

Both class A and B are under namespace Common but under different sub namespaces.

My problem is as follows:

Including the class A inside class B header file is OK But including class B header in class A and declaring a member of type class B in it causes compilation error undefined type 'B'.

I have tried with forward declarations to avoid cyclic dependency. But still error exists.

Actually I am very confused in what order I have to use the inclusions.

NB: I am not posting the code since I just want to know the exact order or method of declaring or including classes in each other.

Any help will be appreciated.

Upvotes: 0

Views: 749

Answers (1)

Arne Mertz
Arne Mertz

Reputation: 24626

  • You have to #include the other class' definition into the header if you use that class as base class or as member variable or if you use it inside an inlined function in the header (including compiler generated special members).
  • You need only a forward declaration if you use the class as function parameter or function return type in function declarations, or if you use poitners or references to it as members.
  • If you use templates instantiated with the class as parameter, it depends on the template and it's use, wether the class' definition is needed or not.

For your case, I assume that the definition of A is needed for B, but not the other way round. You headers should look like this then:

A.h:

namespace Common {
  namespace subnamespace2 {
    class B;
  }

  namespace subnamespace1 {
    class A {
      void foo(subnamespace2::B& b);   //reference, parameter -> fwd-decl
      subnamespace2::B* pB;            //pointer -> fwd-decl
    };
  }
}    

B.h:

#include "A.h"
namespace Common {

  namespace subnamespace2 {
    class B {
      subnamespace1::A a; //direct member -> def needed
      void bar() {
        a.foo(*this);  //inline use -> def needed
      }
    };
  }
}

Upvotes: 1

Related Questions