Search code examples
c++oopprivateencapsulation

Restricting access to methods of a class


I have a class A which has public methods and used by 100 other classes implemented in different applications. Now I want to make those public methods as private so that no new classes access them, but I want the existing client classes to still access them. But I don't want to even touch those client classes , because the owners seldom allow even any ripple in their classes.

I checked

Can I access private members from outside the class without using friends?

C++: Is there a way to limit access to certain methods to certain classes without exposing other private members?

friend class with limited access

But all ( not all really ) demand a change in the client's code. The client code should not change.

One straight forward way is to make all those N classes friends , But I am somewhat not comfortable doing that. Is there any pattern or an acceptable technique ( not a hack please ) to achieve this access restriction? Thank you and I apologize if this is a duplicate.


Solution

  • Classes in C++ are made friends in order to indicate an special intentional strong coupling between classes. This use of friend infact enhances Encapsulation rather than break it as maybe the popular feeling.
    How?
    Without friendship the only non-hack way to expose the functionality to other class would be to provide public, get and set member functions,this in fact breaks encapsulation because all classes(even those who don't need to) now have access to these methods and hence the members increasing the risk of potentially breaking down the class data.

    Back to your situation, If you have a 100 classes which need access to this particular class, then you already had the right design in-place by having those methods as public. Now trying to make those methods private to future classes is a trying to hack your existing design, Your design does not support it.

    Making the existing classes as friends does not ideally fit in the above mentioned criteria and hence is not a good choice for the scenario.
    However, given the situation there is no other way in which you can implement this. Making the existing classes as friend and granting them the special access seems the only way. This is still bad because the 100 classes which only had access to the few methods will now have access to your entire class.