Hiding a C++ class in a header without using the unnamed namespace

丶灬走出姿态 提交于 2019-11-29 14:45:46

You could do an inner class:

class B
{
  class A { /* ... */ };
  A a_;
}

The right way to go about it in C++ is PIMPL idiom. Alternative solution is to put the class you want to hide into a nested namespace, which is usually called detail. But that will not make it totally private as users will still be exposed to its dependencies, and will be able to use it directly.

Instead of class B holding an A object, have it hold an A* instead (or a shared_ptr<A>, or an unique_ptr<A>, etc.). This way class B only needs a forward declaration of class A and class A can be fully defined inside of class B's source file.

If A is an implementation detail of B, don't put its definition in the header at all. Instead:

class B {

   ...
   class A * myA;
};

and then put the definition of A in the B implementation (i.e. .cpp) file.

Document that this class is not part of the public API and should not be used.

In C++ you have to trusted programs that link with your library code because you have little other choice. C++ has limited "access control" features many of which can be bypassed or abused so you're better of treating your API clients with respect and building trust.

If you design your API to be easy to use correctly and hard to use unintentionally incorrectly then you will be helping your clients and it is hardly your fault if your clients abuse your interface.

An unnamed namespace is useless anyways, as it only protects agains multiple definitions. What you could do is either using the pImpl Idiom, as mentioned in other answers, or use a detail namespace. Works fine for Boost:

namespace detail{
  class A{
    // ...
  };
}

class B{
public:
  // ...
private
  A a_;
};

Anyone messing with stuff in a detail namespace is asking for trouble. Or maybe obscure it even more

namespace _b_impl_detail{
  // ...
};

Anyone who now touches anything inside should be shot in the foot. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!