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
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.
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.
Unnamed Namespaces They are directly usable in the same program and are used for declaring unique identifiers.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With