rbaleksandar rbaleksandar - 1 month ago 9
C++ Question

C++ namespaces - forward declaration and visibility of nested namespaces

It's a pretty basic question but I have actually never defined namespaces on my own. I am trying to group the classes in my Qt-based library in various namespaces (and also allows easier expansion without name conflicts). For example the main class (which also represents the library) belongs to the top-level namespace

lib
:

namespace lib {
class LibClass;
}


This
LibClass
uses a bunch of other namespaces and classes which are defined in other header files that are included in the header of
LibClass
:

#include <QObject>
#include "libclass_global.h"
#include "Manager.h"
#include "Configurator.h"

namespace lib {
class LibClass;
}

class LIBCLASSSHARED_EXPORT LibClass : public QObject {
public:
LibClass();
...
signals:
...
private slots:
...
public slots:
...
private:
lib::core::communication::Manager manager; // PROBLEM HERE
lib::core::communication::Configurator configurator; // PROBLEM HERE
}


with Manager.h containing

namespace lib {
namespace core {
namespace communication {
class Manager;
}
}
}

class Manager {
public:
Manager();
...
private:
...
}


and Configurator.h containing

namespace lib {
namespace core {
namespace communication {
class Configurator;
}
}
}

class Configurator {
public:
Configurator();
...
private:
...
}


The contents of the classes are not important here.

Upon compilation I get that
core
in namespace
q3dtp
does not name a type. So basically from what I understand I need to use forward declaration in the header of my
LibClass
since namespace seem not to actually be included with the insertion of the header files that contain those (for some reason):

namespace lib {
class LibClass;

namespace core {
namespace communication {
class Manager;
class Configurator;
}
}
}


The problem with that is that now I'm limited to pointers only since I'm forward-declaring
Manager
and
Configurator
. I'd like to avoid dynamically allocating stuff whenever possible (and not needed).

So the question here is how do I solve this problem? I can obviously move all my class declarations to the same header and their definitions to the same source file. This will however make things rather difficult to maintain in the future. Only declaring the sub-namespaces doesn't seem to solve the problem either - I get that both classes don't name a type and further that
LibClass
doesn't have member names
<name_of_class_from_nested_namespace>
.

Answer

Your declaration of LibClass is wrong. It should be:

namespace lib {
    class LibClass;
}

class lib::LibClass {
    ...
};

or

namespace lib {
    class LibClass {
        ....
    };
}

As it currently stands, you are declaring lib::LibClass and defining ::LibClass (two entirely different classes).

This applies to all your other classes too.

Comments