Access Control for objects - c++

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!");
}

Related

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.

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.
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

In what scenarios should one declare a member function a friend?

In what kind of scenarios would we declare a member function as a 'friend function' ?..What exact purpose does 'friend function' which defies one of central concept of 'Encapsulation' of OOP serve?
You would use a friend function for the same sort of reasons that you would use a friend class, but on a member function (rather than entire class) basis. Some good explanations are in this thread.
While friend functions and classes do violate encapsulation, they can be useful in some scenarios. For example, you may want to allow a test harness to access class internals to allow you to do whitebox testing. Rather than opening up the entire class to the test harness, you could open up a particular function which accesses the internals required by the test harness. While this still violates encapsulation, it's less risky than opening up the entire class.
Also see this article for some more information about friend classes and functions.
Friend functions and classes do not violate encapsulation when you are trying to build an abstraction or interface that must physically span multiple C++ classes or functions! That is why friend was invented.
Those types of cases don't come up often, but sometimes you are forced to implement an abstraction or interface with disparate classes and functions. The classic example is implementing some type of complex number class. The non-member operator functions are given friendship to the main complex number class.
I also recall doing this when programming with CORBA in C++. CORBA forced me to have separate classes to implement CORBA servants. But for a particular part of our software, I needed to marry these together as one interface. Friendship allowed these two classes to work together to provide a seamless service to one part of our software.
Having the ability to mark a particular member function on another class as a friend to your class may seem even stranger, but it is just a way of tightly controlling the friendship. Instead of allowing the entire other class "in" as your friend, you only allow one of its member functions access. Again, this isn't common, but very useful when you need it.
See C++ FAQ Lite:
Sometimes friends are syntactically better (e.g., in class Fred, friend functions allow the Fred parameter to be second, while members require it to be first). Another good use of friend functions are the binary infix arithmetic operators. E.g., aComplex + aComplex should be defined as a friend rather than a member if you want to allow aFloat + aComplex as well (member functions don't allow promotion of the left hand argument, since that would change the class of the object that is the recipient of the member function invocation).
Sometimes public/private/protected protection level is not quite enough for real world situations. So thus we give a small get-out clause that helps without having to make methods publicly accessible.
I personally use this the same way that Java uses the 'Package' protection level.
If I have a class in the same package that needs access I will consider using friend. If it is a class in another package then I will wonder why on earth is this other class needing access and look at my design.
One point that I find relevant: member classes have access to the private parts of the containing class. This may sometimes be a better alternative to "friend".
class A
{
private:
int b;
public:
class MemberNotFriend {
public:
static void test() {
A a;
a.b = 0;
}
};
};
void test()
{
A::MemberNotFriend::test();
}
Here is a simple, concrete example of how I am using a friend function:
I have a game where each sprite object stores its info like X,Y position as private members.
However, I wish to separate the game objects from the rendering: a game object does not need the exact details of how it is rendered. A game object only stores game state, and this game state may be rendered in a number of different ways.
Thus the game object class has a friend function: render(). The render() function is implemented outside the game object class, but it can access the X,Y position position membefrs as needed to render the game object.

Extending an existing class like a namespace (C++)?

I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
Inheritance (as you pointed out), or
Use a function instead of a method, or
Alter the engine code itself, but isolate and manage the changes using a patch-manager like quilt or Mercurial/MQ
I don't see what's wrong with inheritance in this context though.
If the new method will be implemented using the existing public interface, then arguably it's more object oriented for it to be a separate function rather than a method. At least, Scott Meyers argues that it is.
Why? Because it gives better encapsulation. IIRC the argument goes that the class interface should define things that the object does. Helper-style functions are things that can be done with/to the object, not things that the object must do itself. So they don't belong in the class. If they are in the class, they can unnecessarily access private members and hence widen the hiding of that member and hence the number of lines of code that need to be touched if the private member changes in any way.
Of course if you want to access protected members then you must inherit. If your desired method requires per-instance state, but not access to protected members, then you can either inherit or composite according to taste - the former is usually more concise, but has certain disadvantages if the relationship isn't really "is a".
Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.
Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.
You could do something COM-like, where the base class supports a QueryInterface() method which lets you ask for an interface that has that method on it. This is fairly trivial to implement in C++, you don't need COM per se.
You could also "pretend" to be a more dynamic language and have an array of callbacks as "methods" and gin up a way to call them using templates or macros and pushing 'this' onto the stack before the rest of the parameters. But it would be insane :)
Or Categories in Objective C.
There are conceptual approaches to extending class architectures (not single classes) in C++, but it's not a casual act, and requires planning ahead of time. Sorry.
Sounds like a classic inheritance problem to me. Except I would drop the code in an "Engine Enhancements" directory & include that concept in your architecture.