Granting access on a function to another class without exposing it - c++

I have a class let us call it Person:
class Person{
private:
void move(x,y,z);
}
I have another class called PersonController:
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(some_values); //Wrong Accessing to a private member
}
}
private:
Person* controlled_person_;
}
Both Person and PersonController are part of the public interface of the library I am designing.
I want PersonController to be able to call move from Person. However, I do not want anyone to access this function (move) from the public interface.
The easy way to sovle the problem is add a friendship so PersonController can access private members of Person. However, as far as I read the friend keyword was not introduced to solve these kind of problems and using it here would be a bad practice.
Is this correct? Should I avoid friend here?
Does this mean my design is broken?
Any alternative suggestions?

From what you said in comments, it seems you are interested in only allowing PersonController to touch that one member function. The way to do that and only that, is to make the door public, but add a private key for it:
class Person{
public:
class MovePrivilege {
move_privilege() = default; // private c'tor
friend class PersonController; // only PersonController may construct this
};
void move(MovePrivilege, x,y,z);
};
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(MovePrivilege{} , some_values);
}
}
private:
Person* controlled_person_;
};
The type MovePrivilege has a private c'tor. So it can only be constructed by its friends. And it is also required for calling move. So while move is public, the only classes that may call it are the friends of MovePrivilege.
This essentially gives you a fine grained control over who may call move. If this is obtrusive and you can't change move itself, a variant of the attorney client idiom may be appropriate instead.
You do have options at your disposal. Direct firend-ship is just the bluntest tool.

That is exactly the sort of problem that friend is meant for. While friendship should be minimized if your design needs it there is no reason not to use it.
I see non-use of friend a lot like the continuing dislike of 'goto', there are simply times where using it will make a design far cleaner.

Yes your design is not correct.
Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members. You can read more here
So PersonController (If it only control person class) should not be a class because it is not concept of data structures Check if it is possible to merge them or design another way.
There are many ways to do it.If you want to design it like what you do now you can use protected access controller for your function and Create derived class but it's not a good design again.
You can use friend function here too but it isn't an object oriented concept again(But the easiest way).
You should rethink about your design if you want to design it OO.Because you can't access private function from other class in object oriented programming ,It breaks encapsulation so C++ won't let you do that.
However your question depends on opinions too.

Related

Friend Class In C++

here im not understanding the concept very well or i am right.... So lets take this "friend" class example here:
class MyClass{
friend class AnotherClass;
private:
int secret;
}
class AnotherClass{
public:
void getSecret(MyClass mc){
return mc.secret;
}
}
So Yes... in the above code it will actually work if you do it... but in general, why cant you use getters and setters all the time instead of friend class? Is the reason of friend class usage because of "tediousness"?
friend is for when you don't want to expose getters/setters/internals to everyone, but just to a single class. So it's a tool for encapsulation.
For example, if you provided a public getSecret in MyClass, everyone could have access to that private variable even if they shouldn't know about it. This breaks encapsulation. friend is there to fix this problem, so that only those classes that need to know about secret have access to it.
As #nicomp said, "it's like giving your physical friend a key to your house but you don't know what they will do with it". So a friend class has unlimited access to all internals of the class it's friends with. This in unfortunate, but the key (no pun intended) here is to keep classes as small as possible so that this doesn't become a problem, which also would be according to the Single Responsibility Principle.
A public getter or setter permits anybody access. They have some uses, notably for maintaining class invariants when some property is changed, but a getter / setter pair that look like the following code are no better than public member variables for constraining access:
class A {
public:
int getX() const { return x; };
void setX(int x_) { x = x_; };
private:
int x;
};
The getX() and setX() functions do nothing but provide access to x. Everybody can use them, so anybody can change the value of x. There's no point making it private, then.
If, instead, only some classes or functions need to be able to change x, you can make them friends of class A. This restricts the access to only those friends, rather than giving it to everybody.
As such, friend is a tool for encapsulation, permitting the encapsulation to be wider than "just my own class" (private members) or "just my class and classes that derive from it" (protected members). A friend need not be in the same class hierarchy (it need not be a class at all; functions can be friends), but it still permits you to restrict access to only those things that actually need it.
Note that, like getters and setters, it should be used sparingly. Encapsulation is a good thing, and where possible the private members of your class should remain just that – private. friend is a tool that allows you to selectively grant access, but you should always carefully consider whether that access needs to be granted, or whether the function / class that needs it would be better off as a member of your class, instead.
Don't forget about testing and/or copying...
Friend classes / methods can be used quite successfully for checking intermediate states within class functionality.
They can also be useful for some types of copy constructors, where the class to be copied is not a direct ancestor of the target class thus precluding protected members as an option.
Consider the following use-case that I encountered recently: I refactored some code from one class into another class. This new class had to access members from the original class but I did not want to provide this via public getters to avoid other clients messing around with these. In this case, I really welcomed the C++-friendship mechanism.
However, these use cases are very seldom (hopefully, otherwise there is probably something wrong in your SW architecture) and I try to avoid it as much as I can since it is the tightest form of coupling.

Class interface query

I've been wondering about a design that I've been using for quite some time for my game engine and games. Let's say we have an Object class
class Object
{
public:
const std::string& getName() { return m_name; }
private:
std::string m_name;
}
Then, I have a class called ObjectManager, which holds an instance of Object. Now, I've been wondering if I should keep that instance private in ObjectManager and duplicate code so that it could call getName(), or make Object public which defeats the concept of encapsulation. Which design do you guys think is better?
Thanks for any help!
If your class contains an object that is usable by others, expose it. Encapsulation is meant to hide variables needed to do something. Certain data members don't fall into this.
Example:
Person tom;
tom.getEyes().getColor();
tom.getMouth().eat(tomato);
tom.legs().walk();
Person could hide everything but it would be cumbersome:
tom.getEyesColor(); // accessor for every eye feature
tom.eat(tomato);
tom.walkAndEat(); // every possible combination of actions
Further example:
grid.row(3).col(5).setText("hello");
Here a column class could expose many methods without the grid class having to be touched. This is the beauty of object oriented programming.
If you named your class ObjectManager i get the feeling it is managing Object instances for others so you ought to expose it. The other idea to use inheritance is also valid:
class ObjectManager : public Object
{
};
If you want to restrict the interface to methods only then keep the object private and use an accessor method that returns a const reference (and non const if needed) to the private object.
Also, inheritance is a good option if applicable.
It depends on what you're doing. If I understand your question correctly, I'd personally lean more towards making the Object a private member of ObjectManager and adding a function to ObjectManager to act as a proxy for Object::getName(). (Is this your question?) However if you're just wrapping particularly thinly and are not trying to do something particularly technical or what have you, I might be tempted to answer otherwise. It depends, but more than likely, go ahead and make it private and add the extra function. Note that this answer is based on the assumption that you're going to make heavy use out of inheritance here.
It really depends on the situation (Sorry for the non-answer!). If you do want to support strong encapsulation, you would probably want ObjectManager to look something like this:
public class ObjectManager
{
private:
Object obj;
public:
string GetNameOfInnerObject();
}
As you can see I changed the method header to be descriptive with respect to ObjectManager. This type of method naming can come in handy to abstract an object's more complex interactions within itself away.
Edit: It might help if you tell us what ObjectManager is supposed to do. Does it have any methods that don't correspond directly to your inner object?

C++ how to elegantly deal with friendship not being inherited

I have a set of classes
class myClassA{
friend class MyFatherClass;
};
class MyFatherClass{
...
};
class MySonClass : public MyFatherClass {
};
My father class can access all the methods of the class MyClassA.
I would like as well that all the class which will extend MyFatherClass will be able to call such methods.
I can see just 2 options:
at any time I go to add in myClassA the new class as a friend. ( I do not like it )
I create some protected wrapper in the father function to access the method from the class myClassA. (slightly better but i still do not like it as well because i have to create a new wrapper at any time a new method is created in myClassA)
Do you have any idea for a more elegant solution to the problem?
Thanks
First off... what does elegant mean? Less code for you to write? I suggest you don't compromise when it comes to readability.
Using friendship should not be a decision taken lightly. There are numerous threads on SO dealing with this, but here I'll just assume you already know what this implies.
Option 1) is a lot more readable. When someone sees the class, they will directly know who has access to it. Code should be expressive, and this option describes the intent perfectly.
Option 2) is a bit of an overkill. You're writing a wrapper just so you can access some functions... why not make them public to start with, since the wrapper has public access. It's just an added layer of abstraction for nothing.
You should first think about functionality (both work), expressiveness and readability (option 1 is definitely better here).
It's a bit hard to make a judgment knowing so little about the application, but if the functions should only be used by MyFatherClass and its descendents, they should be protected members (perhaps static) of MyFatherClass.
Perhaps MyClassA should be a member of MyFatherClass with no member functions of its own, just a struct to hold some data members.
class MyFatherClass {
protected:
struct myStructA {
int state;
};
static void DoSomething( myStructA &a );
…
};
Just a suggestion… it's hard to tell what's best given so little information. The general idea is that the language disallows friendship inheritance because you can always make a good design without it.

What's the best way to access the internal data structure within a class?

I have a class A consisting of a bunch of internal data structures (e.g. m_data) and a few objects (e.g. ClassB):
class A
{
public:
...
private:
int m_data[255];
ClassB B[5];
}
What's the best way for B to access m_data? I don't want to pass m_data into B's function..
// updated:
Many thanks for the responses. Let me provide more contextual info.
I am working on an AI project, where I got some data (e.g. m_data[i]) at each time step. The class A needs to buffer these information (m_data) and uses a list of B's (example updated) to make inference. Class B itself is actually a base class, where different children derive from it for different purpose so I guess in this context, making B a subclass of A might not be clean (?)..
friend class ClassB;
Put this line anywhere in A's declaration if you want ClassB to access all of A's protected and private members.
One of:
Make ClassB a friend of A
Make A a sub-class of ClassB and make m_data protected rather than private
[In response to Mark B's comment]
If ever you feel the need to resort to a friend relationship, the design should be reconsidered - it may not be appropriate. Sub-classing may or may not make sense; you have to ask yourself "Is class A and kind of class ClassB?" If the question makes no sense intuitively, or the answer is just no, then it may be an inappropriate solution.
Ideally, you don't allow external access the data structure at all. You should rethink your approach, considering more the question "What are the functional requirements / use cases needed for ClassB to access instances of A" rather than offloading the management of the internal members to methods not managed within class A. You will find that restricting management of internal members to the class owning those members will yield cleaner code which is more easily debugged.
However, if for some reason this is not practical for your situation there are a couple possibilities that come to mind:
You can provide simple get/set accessor methods which, depending upon
your requirements, can be used to access either a copy of or a
reference to m_data. This has the disadvantage of allowing everybody
access, but does so only through well defined interfaces (which can
be monitored as needed).
ggPeti mentions use of friend, which may work for you, but it gives ClassB access to all of the internals of A.
A getData() function that returns m_data.
Use setData() to change the value.
So in the function in class B you would create a pointer to the class type A variable that you created. Lets just call this pointer 'p'.
Just do p->getData(), p.getData() may be the answer. I think they do the same thing but c++ uses the '->' and some other languages use the '.'. Don't quote me on that one though.
Good luck, sir. Hope I helped ya.
What's the best way for B to access m_data?
Depends on the use.
This is how would I do it :
class ClassB
{
// ...
void foo( A &a )
{
// use a's data
}
};
class A
{
//...
int m_data[255];
ClassB & B;
};
Depending on the implementation, maybe ClassB is not needed at all. Maybe it's methods can be converted to functions.

Can there be two public section in a class? If yes then why ? And in which circumstances we do so?

There is something bugging me about classes. For example
class A
{
public:
A()
{
.....
.....
}
void cleanup()
{
....
....
....
}
public:
UINT a;
ULONG b;
};
In the above example there are two public section. In the first section I am defining a constructor and a method and in the second section I am declaring data members. Is the above class i.e. A correct. Can we do that? If yes then why is that needed and in what circumstances should we use it? Since we can do the entire thing in one section then why are there two sections?
Access qualifiers simply apply to the code that follows until the next qualifier. There is no restriction on the number or order of such qualifiers.
It is generally not necessary to repeat the same access qualifier in a class, and doing so is likely to confuse the reader. They also may have an effect on the layout of a class, since data members following the same qualifier must be laid out in the order they are declared, but there is no such restriction between qualifiers.
As Marcelo says, you can use the public, private and protected qualifiers as many times as you wish. "When" is entirely personal. Some people like this:
class AClass
{
public:
// all the public stuff
protected:
// all the protected stuff
private:
// all the private stuff
};
but personally (and this really is just a personal preference) I like to do this:
class AClass
{
// constructors and destructors
public:
// public cons/dest
protected:
// protected cons/dest
private:
// private cons/dest
// accessors
public:
protected:
private:
// methods
public:
protected:
private:
// members
public:
protected:
private:
};
Feel free to come up with your own style, whatever you're comfortable with. There is no right or wrong way of doing it. Just try to be consistent.
Yes its correct however personally I prefer to just have one public section at the top of the class, that's where programmers looks first when examining a new class. It is then easier to see which parts are supposed to be accessible and which are not -- instead of browsing the whole class header.
I usually try to arrange the declaration of the class so that it's easy for others to use the said class.
The usual is thus: public/protected/private, in this order, because it simplifies life for the readers.
People who use the class can stop reading once reaching the protected tag, anything after is none of their concern.
People who derive from the class can stop reading once reaching the private tag, anything after is implementation detail.
This, coupled with not writing the code of the methods at their point of declarations, makes for an easy to read interface.
There are however a couple of tricks:
when using metatemplate programming, you may need to declare types first, methods afterward, so you end up with 2 series of public/protected/private
when using the Key idiom (instead of friend), you have a public section that is in fact dedicated to only a small portion of the users and is best isolated either at the bottom of the normal public section or after the protected section.
Finally, as to comment about the layout issue among the attributes. Encapsulation means that attributes should be private. So, either you have a struct and everything is public or you have a class and everything is private, mixing the two means breaking encapsulation, and that's a bug in the making.
The class is correct, public is just a access qualifier and will apply till the next qualifier is seen or the end of class declaration. There is no limit to how many of these access qualifiers(public, private, protected) you can have in a class. As to why this is useful, it helps writing class declarations the way you want. For example I might want all the member functions (public,protected or private) declared before the (say) private data members.
As #Marcelo Cantos's answer explains, this is allowed. When writing code yourself you should avoid this, as it only leads to confusion when others read your code. The only place I have ever seen this in real life is in the code generated by various MFC-wizards. Whenever you add some thing to your class using a wizard, it would just add an extra section to the end of your class.