19

Assume having a C++ class. And there's a namespace which should be visible only inside my class. What to do for that?

class SomeClass
{
    using namespace SomeSpace;

public:
    void Method1();
    void Method2();
    void Method3();
};

namespace SomeSpace
{
    /*some code*/
};
antpetr89
  • 1,143
  • 3
  • 12
  • 14
  • 1
    What exactly do you mean by visible? Namespaces are not something like private/public. – KillianDS Feb 15 '12 at 15:55
  • One option is to put the class *inside* the namespace. If it depends so much on that namespace, why is it outside? – Bo Persson Feb 15 '12 at 16:11
  • Possible duplicate of [Why can't I put a "using" declaration inside a class declaration?](https://stackoverflow.com/questions/2134844/why-cant-i-put-a-using-declaration-inside-a-class-declaration) – underscore_d Jul 02 '17 at 13:54

2 Answers2

11

using namespace X; is called a using directive and it can appear only in namespace and function scope, but not class scope. So what you're trying to do is not possible in C++. The best you could do is write the using directive in the scope of the namespace of that class, which may not be desirable.

On second thought, though, analyzing your words,

Assume having a C++ class. And there's a namespace which should be visible only inside my class. What to do for that?

I'd suggest something like the following, which I am not sure is what you want.

class A
{
public:
    void Method1();
    void Method2();
    void Method3();
 
private:
 
    class B
    {
       //public static functions here, instead of namespace-scope
       // freestanding functions.
       //these functions will be accessible from class A(and its friends, if any) 
       //because B is private to A
    };

};
Matt Howell
  • 15,750
  • 7
  • 49
  • 56
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • Nested classes can be so tempting because of how convenient they seem. However, the major - and I think underreported - drawback of nested classes is that, like any other class member, all of the nested class's members get full access to all private/protected members of the enclosing class. For cases (perhaps a majority?) where that wasn't the specific goal and reason for using nested classes, then they basically completely break encapsulation. – underscore_d May 24 '17 at 22:12
1

No but you can do it like that:

namespace SomeSpace
{
    /*some code*/
};

using namespace SomeSpace;

class SomeClass
{

public:
    void Method1();
    void Method2();
    void Method3();
};

Though it is not recommended either to apply the using namespace directive in header files and often considered as a bad style. It is OK to put in in a source file (.cpp) of your class.

Dmitriy Kachko
  • 2,804
  • 1
  • 19
  • 21