Rubens Rubens - 11 days ago 5
C++ Question

Hiding declaration in cpp file

I have a file

decl.h
with the following:

namespace foo {
...
class A;
...
}


I want to use the whole of declarations from
decl.h
, except for
class A
, as I want to have another class, with the same name, declared and defined inside my
def.cpp
. I'm looking for something that'd allow me to do this:

# include "decl.h"
using namespace foo;
hiding foo::A;

class A {
...
};


Is there anything like that? Or the only way around is to explicitly make each desired member from
foo
public in my
def.cpp
?

Answer

You can't hide members of a namespace, and certainly not when using a using namespace ... statement.

The whole point of namespaces is to avoid naming conflicts like you describe.

So, get rid of the using namespace foo; statement, and wrap the second class A in a different namespace, eg:

#include "decl.h"
//using namespace foo;

namespace defcpp {

class A {
    ...
};

}

Now def.cpp will know about foo::A and defcpp::A. You just have to qualify which one you want to use whenever you need to use an A. For example:

#include "decl.h"
//using namespace foo;

namespace defcpp {

class A {
    ...
};

}

class B {
    defcpp::A a;
    ...
};

void doSomething()
{
    defcpp::A a;
    ...
}
Comments