Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to friend a class in an anonymous namespace in C++?

I am porting code from Java to c++ and I'd like to replicate some anonymous functionalities.

In file A.h I have :

class A { private:   int a;    class AnonClass;   friend class AnonClass; }; 

In file A.cpp I have :

namespace {   class AnonClass   {   public:     AnonClass(A* parent)     {       parent->a = 0; // This doesn't work, a is not accessible     }   } } 

Is it possible to friend a class in an anonymous namespace in C++?

In Java you can declare anonymous classes so it would be very similar. Also it would not expose AnonClass to clients of A.h

like image 696
Eric Avatar asked Nov 09 '13 05:11

Eric


People also ask

What is the point of anonymous namespace?

An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.

What is a friend class in C?

A friend class in C++ can access the private and protected members of the class in which it is declared as a friend. A significant use of a friend class is for a part of a data structure, represented by a class, to provide access to the main class representing that data structure.

Why do we use unnamed namespace?

Unnamed Namespaces They are directly usable in the same program and are used for declaring unique identifiers.

Can a class be a friend of another class in C++?

A class Y must be defined before any member of Y can be declared a friend of another class. In the following example, the friend function print is a member of class Y and accesses the private data members a and b of class X . You can declare an entire class as a friend.


1 Answers

Less known alternative is to make class Anon a member class of A. Inside class A you only need a line class Anon; -- no real code, no friend declaration. Note it goes within class A, almost as in Java. In the .cpp file you write all the details about Anon but you put it not in anonymous namespace but withinA::

  class A::Anon { ..... }; 

You can split declaration and implementation of A::Anon, as usual, just remeber always add A:: to Anon.

The class Anon is a member of A and as such gets access to all other members of A. Yet it remains unknown to clients of A and does not clutter global namespace.

like image 87
Michael Simbirsky Avatar answered Nov 06 '22 00:11

Michael Simbirsky