I am looking at other's code and find one part I can't understand.
class a {
public:
function xxx () {.....}
}
class b : public a {
public:
xxxx
protected:
constructor()....
friend class a ; <= here why it is needed ????
}
As I understand, since b had already inherited from a, it should be able to use the function of a directly. What's the purpose of this "friend" declaration used for?
The friend allows a to use b's methods, not the other way around, which isn't implicit.
The design looks fishy though, a base class shouldn't care about derived classes.
friend class a; grants class a the right to access non-public members of b. So in this small example, an instance of a can call b::constructor(). Without friendship, it wouldn't be possible.
As to why, there is not enough information to answer that, other than there must be a need for instances of a to call b::constructor() (assuming that to be anything other than the syntax error it currently is).
As I understand, since b had already inherited from a, it should be able to use the function of a directly.
Yes. The friend specification though allows access the other way around (instances of a will be able to access private data and functions of b).
What's the purpose of this "friend" declaration used for?
The example above doesn't suggest any. The only situation where it may make sense is with using CRTP in certain situations (i.e. a is a template of b) but even so, if you see such a requirement ("must add friend declaration in b") it is possible that the design you're looking at is flawed.
Can you post a concrete example?
Depending on your projects/requirements, your class designs change. I have no comment on your class hierarchy but true your question is all about theories of friend usage. If you don't use friend, you will not be able to call B members from A. It is there for...cross-mating :D
It almost certainly means that there is a serious design problem. One of the basic rules of thumb for inheritance is that base classes should not need any information about derived classes. Making a a friend of b makes it possible for member functions of a to get at the internals of b objects.
Related
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.
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.
Suppose there are two classes A and B:
class A {};
class B {};
In what aspects differ the two examples below?
Example 1:
class C : public A, public B {};
Example 2:
class C
{
//private
friend class A;
friend class B;
}
A friend can touch the private parts (pun only slightly intentional! ;) ) of whatever it is friend of, but nothing of A and B are part of C - it just means that "A and B can touch C's private bits"). Anything "less" than private is of course also available to A and B, so if C has protected or public members, that will also be available.
When you inherit, the A and B becomes part of C. Any private sections of A and B are not available to C. In the "is-a" vs. "has-a" nomenclature, C now is-a A and is-a B - in other words, it's inherited from A, so it "behaves like A from an interface perspective.
There are several big differences. Inheritance and friendship are very different.
With friendship, class C is NOT an instance of class A or class B. Therefore, if you have a function like:
void processMyClass(A* a);
you cannot pass it an instance of C whereas, if C subclasses A (publicly), it IS an instance of A.
With friendship, class A and B can touch all the private member data and functions of C. With inheritance, class C can touch the public and protected members of A and B.
Friendship is not inherited. This means, for example:
class D : public C
{
private:
void foo() {
// A and B cannot call this function
}
}
In the context you're using, to answer your question to the best of my ability, friends simply allow your classes to share protected/private data, while inheritance will do the same, except there'll be a deeper relationship, where the classes are one in the same (such as with casting).
While the answers you've gotten are reasonably accurate, I don't think they're really complete. In particular, although they explain what the difference between friendship and inheritance is, they don't really explain much about which you should use when, or how the difference affects your code.
The primary use of inheritance (in C++) is to define an interface in a base class, and implement that interface in each of a number of derived classes. The parts of the interface that a derived class must implement will normally be signified by pure virtual functions in the base class.
The primary use of friendship in C++ is to define something that forms part of an interface, but for syntactical reasons can't be a member function. One extremely common example is a stream insertion or extraction operator. To implement these as member functions, they'd have to be members of the stream class. Since we don't want to modify the stream class constantly, they're instead free functions that take a reference to a stream as their left parameter, and a reference to a (possibly const) object of the type they insert/extract as their right operand.
These don't necessarily have to be friends of the class--they can be written to use only the class' public interface. If you do that, though, it generally means the class is exposing more in its public interface than is otherwise necessary. The interface is no longer minimal, which tends to indicate a problematic design.
One note though: you can define a friend function inside a class definition:
class Foo {
// ...
friend std::ostream &operator<<(std::ostream &os, Foo const &f) {
// ...
}
};
At first this may seem strange (and syntactically it is, somewhat). Even though it's defined inside the class definition, the friend means that this is not a member function. At least in my opinion, this reflects its situation fairly accurately: conceptually, it's part of the class. It has access to private members, just like any other member of the class. The fact that it's a free function rather than a member function is purely an implementation artifact that has essentially nothing to do with the code's design.
That also points to another difference between friendship and inheritance: with inheritance, you're normally dealing primarily with member functions. Each member function still receives a this pointer, so each member function is directly associated with a specific instance of the class. Yes, you can define it to also receive (a pointer or reference to) another instance of the class if desired, but it always receives this, regardless. A friend (function or class) doesn't get this--the friend declaration just means that the names that are private to that other class are visible to the friend. To get access to an actual instance of that class, you typically need to pass it as a parameter, or something on that order.
Finally, I'll note that the preceding sort of ignores the possibilities of private or protected inheritance. Private inheritance normally means that the derived class is implemented in terms of the base class. This can be handy if (for example) the derived class is similar to the base class, but isn't related in the design--i.e., you're not asserting that an instance of the derived class can be used anywhere an instance of the base class was needed. Its use of the base class is an implementation detail that the rest of the world doesn't need to know or care about.
Protected inheritance is pretty much a mistake. It's allowed because it's consistent with public, private and protected members (which do make sense) but for inheritance, protected simply doesn't seem to accomplish anything useful.
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.
This is an interview question. I am not a C++ expert yet so i need some help in finding the answer to this question ( i first want to understand the question...is it a valid question?)
Question:
Suppose I have a class B that derives
from class A and I wanted to reuse
some, but not all of the methods of A.
How would I restrict access to the
superclass' methods selectively?
thanks!
I assume that
you cannot change the definition of A
you want to select which methods from A should be accessible from a B object.
The using directive solves your problem. Example:
class A
{
public: // or protected for that matter
void foo();
void bar();
};
class B : private A // or protected, depending on whether
// you want subclasses of B to expose
// some methods from A themselves
{
public:
using A::foo;
};
makes foo usable from class B, but not bar. But as a caveat, note that using A::foo will expose all overloads of foo.
The answer they probably want to hear is that you can put the methods to be reused in the protected section of the base class, the methods which should not be visible to the derived classes should go into the private section.
However, taking a step back, you might be able to score extra points by pointing out that there might be better measures for reusing code, depending on what the functions do (such as using free functions which are not visible in a header file).