4

I have a x.cpp file in which i see a class being defined inside namespace. So, my question is :

1) What is the advantage of defining a class inside the namespace? 2)Secondly, i also see structures defined out of the namespace in the same x.cpp file. So, what is the benefit of doing so in the same x.cpp file?

x.h looks like something as follows:

 class x{
 private:
  struct abc;
  };

And x.cpp looks as:

 namespace{
     class{};
 }
 struct x:abc{};
golu kashyap
  • 213
  • 2
  • 5
  • 10

1 Answers1

4

The anonymous namespace is accessible only within its compilation unit. This means that no other cpp can access anyting within the anonymous namespace of x.cpp.

namespace {
     class abc {};  // this class is visible only within x.cpp 
                    // no other separately compiled cpp can't see it. 
 }
struct x : abc{};   // the struct (class) x inherits from abc.      

The advantage is that it makes implementation really private. The only access to abc, is via x which inherits from abc.

This makes it really different from private members or even private inheritance. As you can't absolutely not refer to abc in other compilation units, you can only use forward declaration of x. Thus x is doomed to stay an incomplete type outside x.cpp .

In fact, this approach is the first step towards a perfect PIMPL implementation. This interesting article demonstrates a complete example for implementing PIMPL idiom with anonymous namespace.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • ok, the first part is clear and x is not inherited by abc its syntax is as follows: struct x::abc{}; So, what is benifit of doing this? – golu kashyap Mar 14 '15 at 11:55
  • @golukashyap so you can refactor a 1000 line monster function to 200 static functions and 200 private classes without anyone noticing anyting. – user3528438 Mar 14 '15 at 12:17
  • With a `::` it's diferent approach but same philosophy. If you have a private struct declared in the header, the users of the header can only use it as an incomplete type (i.e. via pointers), but don't see the content. In your x.cpp the statement `x::abc { }`; defines the `abc` which is in `x` using scope resolution operator. (similar syntax as member function). – Christophe Mar 14 '15 at 12:39