Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forward declaration and namespaces (c++)

My Problem:

Got two classes, class A and B, so i got A.h and A.cpp and B.h and B.cpp. A needs to know B and B needs to know A. I solved it the following way (i don't know why it has to be so...)

A.h:

#include "B.h"
class A{ ... 

A.cpp:

#include "A.h"

B.h:

#include "A.h"
class A; // forward declaration
class B { ... 

B.cpp:

#include "B.h"

I used one forward declaration and it works.

The Problem is, that both classes need to be in the namespace "ui". Or at least I think this is the meaning:

A.h:

#include "B.h"
namespace ui{
  class A;
}

class A{ ... 

B.h:

#include "A.h"
namespace ui{
  class B;
}

class B{ ... 

This doesn't work anymore. What do I have to do now to make it work again with namespace and forward declaration?

Both have to be in this namespace. I'm working with Qt and the lines "namespace ui{" etc. are needed. And both classes need to know each other. I already tried just to make this:

namespace ui{
 class A;
 class B;
}

in both headers, but this doesn't work...

Btw: All Header-Files also got the "ifndef"-mechanism.

like image 950
Obs Avatar asked Jun 22 '11 19:06

Obs


2 Answers

Apart to forward-declare the class from within its namespace (as other answers correctly say), remember to either use (prepend) that namespace when referring to the forward-declared class, or add a using clause:

// B.h
namespace Y { class A; } // full declaration of
// class A elsewhere

namespace X {
    using Y::A;   // <------------- [!]
    class B {
        A* a; // Y::A
    };
}

Ref: Namespaces and Forward Class Declarations

like image 160
Campa Avatar answered Oct 26 '22 15:10

Campa


// A.h
namespace ui {
   class A; // forward
   class B {
   };
}



// B.h
namespace ui {
   class B; // forward
   class A {
   };
}



// A.cpp
#include "A.h"
#include "B.h"



// B.cpp
#include "A.h"
#include "B.h"
like image 40
Jörgen Sigvardsson Avatar answered Oct 26 '22 13:10

Jörgen Sigvardsson