Restricting access to methods of a class - c++

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.

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.

I think you can extract an interface of the A class (let it be IA) and make A to implement IA. You should not define those public methods in IA at all.
Then, old code will continue using A and will have access to A public methods, while new code will use restricted interface, that code would receive through some fabric .
Of cause, this can be unimplementable, if you need to (copy-)construct class, or smth like this, but I can't say it now without knowing the usage of class.
Also, you get a little overhead due to virtual functions

Related

What is a public interface in C++ [duplicate]

What are public, private and protected in object oriented programming?
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private - Only the current class will have access to the field or method.
protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public - Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
They aren't really concepts but rather specific keywords that tend to occur (with slightly different semantics) in popular languages like C++ and Java.
Essentially, they are meant to allow a class to restrict access to members (fields or functions). The idea is that the less one type is allowed to access in another type, the less dependency can be created. This allows the accessed object to be changed more easily without affecting objects that refer to it.
Broadly speaking, public means everyone is allowed to access, private means that only members of the same class are allowed to access, and protected means that members of subclasses are also allowed. However, each language adds its own things to this. For example, C++ allows you to inherit non-publicly. In Java, there is also a default (package) access level, and there are rules about internal classes, etc.
All the three are access modifiers and keywords which are used in a class.
Anything declared in public can be used by any object within the class or outside the class,variables in private can only be used by the objects within the class and could not be changed through direct access(as it can change through functions like friend function).Anything defined under protected section can be used by the class and their just derived class.
A public item is one that is accessible from any other class. You just have to know what object it is and you can use a dot operator to access it. Protected means that a class and its subclasses have access to the variable, but not any other classes, they need to use a getter/setter to do anything with the variable. A private means that only that class has direct access to the variable, everything else needs a method/function to access or change that data. Hope this helps.
as above, but qualitatively:
private - least access, best encapsulation
protected - some access, moderate encapsulation
public - full access, no encapsulation
the less access you provide the fewer implementation details leak out of your objects. less of this sort of leakage means more flexibility (aka "looser coupling") in terms of changing how an object is implemented without breaking clients of the object. this is a truly fundamental thing to understand.
To sum it up,in object oriented programming, everything is modeled into classes and objects.
Classes contain properties and methods.
Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other .dlls or even other applications.
These are access modifiers.
All the data and functions(behaviours) are encapsulated or bounded into a single unit called a class. In order to access the properties and behaviour of the class we use objects. But it's also important to decide which behaviour or property has to be exposed or should remain accessible to all the classes and which behaviour or property has to be private.
So, that's when access modifiers like public, private, protected and protected internal help in doing so. This act of defining privilege to the class or method or property is called as abstraction.

What is the role of private members?

#include<iostream>
class student
{
private:
int roll_no;
int standard;
public:
void input();
void display();
};
I asked my teacher about the significance of making some class members private and some members public. He said that data members are usually made private for security reason. He said that no object can access private things of a class, thats why they are secure.
My question is:
When we will develop software, we will be distributing executable files to users. Users will not be able to edit the code. What type of security our teacher is talking about? When I have created the entire code, how someone can edit it? What is the need to think about security?
No your teacher would not be correct that encapsulation, as this is called, is for security. Encapsulation is actually there for a few other reasons:
Creates better maintainability of code. When all the properties are private and encapsulated, it is easy for the writers of the code to maintain the program simply by changing the methods.
Have a Controlled Environment. Encapsulation lets the users use the given objects, in a controlled manner, through objects. If encapsulation didn't exist, client code could use the members of your class in any way they wanted, while member functions limit this to a specific behavior.
Hide Complexities: Hiding the complexities irrelevant to the users. Sometimes, some properties and methods are only for internal use and the user doesn't have to know about these. This makes it simple for the user to use the object.
An example that illustrates what would happen if you didn't have encapsulation:
Suppose you had a class called Human, with a member called age that is public. Now, if someone wanted to modify this, say, based off input, then they would have to check to see if the input is not negative or not a huge amount every time, unless they make a function for it. Now if there was a member function instead that provided access to age, then it wouldn't be client code's problem anymore, since the setter for the field would take care of it as it would be the responsibility of the class to make sure its fields are valid.
This will not affect users of an application, but the teacher is trying to make you safe from your own mistakes.
Keeping member variables private, when possible, protects you from accessing and changing them accidentally from places in your code where you shouldn't do that.
It also makes is clear for the users of the code which variables and functions are intended to be used from outside the class and which are not, thus clearly defining the API of the class.
Just like each person knows their own secrets and it is somehow dangerous to tell others, private members are not exposed to other classes because it may break something in the class and other classes don't really need to know them.
However, people need to communicate to fulfill their needs. We talk, explain our thoughts to be understood.. well, public members are like this, they are needed for the class itself communicate with other classes.

C++ class design

Maybe this is not pure c++ technical question, but any advice is highly welcome.
I need to implement class with many members (let's say A).
I also need to access these data by set of other classes and this access should be quite fast (drawing stuff conditioned by members from class A).
First approach was to set access level inside A as private and use kind of setters/getters to get particular elements to check (so many method calls).
Other approach, just make everything public in A, next one to make dozen of friend classes. To be honest, i do not like any of the above. Rest of system shouldn't have access to A class members at all, only interested ones.
Maybe someone had to deal with something similar and could advice some good practice, maybe some appropriate design pattern?
If your class is more than a dumb collection of data and flags, the proper approach would be to add whatever you are doing with the data into the class, instead of exposing it with get/set.
For example, if you are pulling coordinates, colors, and line thickness from a class 'Polygon' to draw it, you should instead add a method into the class that does the drawing (and pass the drawing context in as a parameter).
Of the two options I would prefer the getter/setter way, because public members are not a good idea especially if most parts of your system mustn't access these members.
So (even if your question is enough general and greedy of details) if you are worried by "uncontrolled access" maybe a solution could be
declare members private( at most protected, if base class has some subclass that can access to them)
use getters/setters for the members that can be reached by everyone
use friend class(or friend methods to access to private/protected members that shouln't be accessed by random classes).
Finally, you should try to reduce the amount of different classes accessing to your members, as far as possible,defining a common virtual class in order to provide a common set of valid methods for every subclass.

Why is public inheritance advocated when reducing the publicly visible API seems preferable from a maintainability perspective?

I am using bada and refer to the tutorial here, which begins:
class MainForm:
public Osp::Ui::Controls::Form,
public Osp::Ui::IActionEventListener,
public Osp::Ui::ITouchEventListener
{
I am running code where I recently removed the public specifier to cut down on my public API. You'll see that the functions implementing those interfaces where all also declared publicly, for which I saw no need and made private. I would do this without hesitation when implementing my own interfaces when those interfaces may provide more access than I would wish regular clients of my concrete class to receive.
What is the reason for making them public, what am I missing?
I guess it is advocated to aid extensibility, but for a dev making apps not libraries I would challenge this wisdom.
If Form, IActionEventListener and ITouchEventListener already support many usable methods, in most cases why hide them? On the contrary: if you hide them and in the future someone will need them, it will be harder for you to maintain the class because you'll need to provide them again.
If you need to hide the parent's methods, there's another way to do this: instead of inheriting, enclose the "parent" as a field in your new class.
In some languages such as C#, public inheritance is the only option.
For me private inheritance of "interfaces" is a non sens.
The interface of an object is its set of public methods. As llya said, if you want to use the functionalities provided by a class internally, use object composition. If you want to provide a subset of the interface, then either compose or simply declare a more restrictive interface.
If the "interface" and the functions taking object from this interface are in a third party library then its means that the developers wanted to force you to implement every methods, so you have to provide them.

Access Control for objects

Is it Possible to limit the functionality of class to certain objects only (in C++). What that would mean is, suppose there are 10 methods in a class and this class has 10 objects. Is it possible to have object1 & object2 access only 3 functions.
Object3, object4,object5, object6 access 6 functions.
and rest of the objects access all functions?
I am trying to implement an access control system, where general users can see only some limited functionality. Previlaged users can have little bit more access and administrators have access to all functions.
One approach is to use inheritance, something like this:
class PublicFeatures
{
public:
// add some methods here;
};
class ProtectedFeatures:public PublicFeatures
{
public:
// add some more methods here;
};
class AdminFeatures:public ProtectedFeatures
{
public:
// add rest of the methods here;
};
In this case, we instantiate objects of any of three classes depending on the kind of access level we want. But what i am thinking is having just one class, and somehow restrict the access to some methods for that particular object.
Is it possible to do such a thing? or i have to follow a different approach for implementing access control?
As far as I know, no. This is part, however, of Aspect Oriented Programming research. I saw something like what you need in this book: Aspect Oriented Software Development.
The main issue you face is the lack of knowledge of "who is the caller" of your function. You could get along by requiring each caller to call your object's methods passing this as a form of authentication about itself. Far from perfect, but with this solution you can wrap each method in a pre-method doing the ACL.
Another alternative would be to declare your implementation class totally private in terms of methods, and define a "bodyguard" class, declared friend of the first. The bodyguard class performs the calls on behalf of the caller (which is the only one authorized to do, due to the friend declaration). You still have the problem of authentication, and you are basically wrapping the whole target class behind its bodyguard object.
Class member access levels don't really have anything to do with users and security restrictions. They're really just coding constructs, not something that you can use at runtime. The compiler is either going to allow or prevent you from calling a function when it compiles your code. If it compiles your program can be run, otherwise not. There's no meaningful way to add in any kind of conditionals or application logic.
But what I am thinking is having just one class, and somehow restrict the access to some methods for that particular object.
Yes, that's what you should do. The language won't help but you can just guard calls to the methods yourself. As in, don't even attempt to call an administrative method if the user is not an admin.
if (user.isAdministrator()) {
securityLogs.archiveAndDelete();
}
else {
throw SecurityException("You can't do that!");
}