C++ Idiom – Attorney | Filtered Access to friend members


Grant access to only selected member function to the friend class.


C++ provide no way to Control the granularity of access to the implement details of class. Friend declaration in gives complete access to the internals of class. Friend decleration follow Nothing-or-Everything proposition. Which is enough to break the carefully crafted encapsulation.

For a very quick example consider a code below


In above code snippet I was only supposed to grant acces to function A() and B() but the friendship in c++ will not let me filter the access. Ans this is where Attorny Iodiom come handy.

Solution and sample code

Attorney Idiom makes us to add a level indirection. We will declare the attorny class as the friend of the orginal base class that we want to add a filtered access control. After protecting the attorny client with private modifier we will finally add the client class as friend of attorny class. Look at the example below.


Everything is shown in code and I tried best to make it concise as possible. Note that I am mentioning twice that we are putting everyting in attorny class as prvate just to protect any other unintended acces through object (what is what all we are doing for.) the static decleration is to make the callingprocess more straight forward we could had also added inline specifier but for now it’s okey.

Now the code itself become more expressive and we added more safety to our code. We are also rewarded with more better encapsulation. We can also make another attorney class to give access to C() of class Fixed separately. It is possible to have multiple attorney classes providing access to different sets of implementation details of the client


You have the power

You can Edit this article or even Submit new articles. Want to Learn more?