EzDevInfo.com

friend

An extensible authentication and authorization library for Clojure Ring web applications and services.

Friend scope in C++

If I have three classes, A, B, C. A and B are friends (bidirectionally). Also, B and C are friends (bidirectionally). A has a pointer to B and B has a pointer to C. Why can't A access C's private data through the pointer?

Just to clarify: This is a pure theoretical C++ language question, not a design advice question.


Source: (StackOverflow)

When should you use 'friend' in C++?

I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

What is a good example of using friend?

Edit:

Reading the FAQ a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?


Source: (StackOverflow)

Advertisements

C++ friend inheritance?

Does a subclass inherit, the main class' friend associations (both the main class' own and other classes friended with the main class)?

Or to put it differently, how does inheritance apply to the friend keyword?

To expand: And if not, is there any way to inherit friendship?

I have followed Jon's suggestion to post up the design problem:
C++ class design questions


Source: (StackOverflow)

PHP equivalent of friend or internal

Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior?

Edit: Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did.

I have classes which are doing C-style system calls on the back end and the juggling has started to become cumbersome. I have functions in object A which take in object B as a parameter and have to call a method in object B passing in itself as an argument. The end user could call the method in B and the system would fall apart.


Source: (StackOverflow)

Template friend

I'd like to do the following:

template <typename T>
struct foo
{
    template <typename S>
    friend struct foo<S>;

private:
    // ...
};

but my compiler (VC8) chokes on it:

error C3857: 'foo<T>': multiple template parameter lists are not allowed

I'd like to have all possible instantiations of template struct foo friends of foo<T> for all T.

How do I make this work ?

EDIT: This

template <typename T>
struct foo
{
    template <typename>
    friend struct foo;

private:
    // ...
};

seems to compile, but is it correct ? Friends and templates have very unnatural syntax.


Source: (StackOverflow)

some friend functions don't follow the rule

For the following snippet:

class A{
    friend void f(){};
    public:
        A(){f();} //error
};

class B{
    friend void f(void* ptr){};
    public:
        B(){f(this);} //no error
};

According to the rule that although friend functions can be defined inside a class, yet they are not visible until they are declared somewhere outside the class scope, the error in the definition of class A is explained.
But I am confused why the snippet for class B doesn't produce the same error as class A's.

Please can anyone tell me about this?


Source: (StackOverflow)

Is this key-oriented access-protection pattern a known idiom?

Matthieu M. brought up a pattern for access-protection in this answer that i'd seen before, but never conciously considered a pattern:

class SomeKey { 
    friend class Foo;
    SomeKey() {} 
    // possibly make it non-copyable too
};

class Bar {
public:
    void protectedMethod(SomeKey);
};

Here only a friend of the key class has access to protectedMethod():

class Foo {
    void do_stuff(Bar& b) { 
        b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
    }
};

class Baz {
    void do_stuff(Bar& b) {
        b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
    }
};

It allows more fine-granular access-control than making Foo a friend of Bar and avoids more complicated proxying patterns.

Does anyone know whether this approach already has a name, i.e., is a known pattern?


Source: (StackOverflow)

'Friends' equivalent for Java? [duplicate]

having a little architectural trouble here.

In C++, we have the notion of 'friends,' where such friend classes can access private members.

So, I'm deving a Java app and trying to adhere to the MVC architecture. I've got a controller class that manages graph connectivity between 'map_objects.' I'd like to hide the function in the DTO 'map_objects' that actuall sets up these connectivities, by using this controller class.

(Ie, even if the controller class implements the required functionality of setting up connectivities, the 'users' can still access setter/getter functions in the the DTO directly to set them up themselves.)

Are there any design patterns or tips in this regard? (Or have I totally mucked up?)

DUPLICATE http://stackoverflow.com/questions/182278/is-there-a-way-to-simulate-the-c-friend-concept-in-java


Source: (StackOverflow)

friend declaration declares a non-template function

I have a base Class akin to the code below. I'm attempting to overload << to use with cout. However, g++ is saying:

base.h:24: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, Base<T>*)’ declares a non-template function
base.h:24: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning

I've tried adding <> after << in the class declaration / prototype. However, then I get it does not match any template declaration. I've been attempting to have the operator definition fully templated (which I want), but I've only been able to get it to work with the following code, with the operator manually instantiated.

base.h

template <typename T>
class Base {
  public:
    friend ostream& operator << (ostream &out, Base<T> *e);
};

base.cpp

ostream& operator<< (ostream &out, Base<int> *e) {
    out << e->data;
return out;
}

I want to just have this or similar in the header, base.h:

template <typename T>
class Base {
  public:
    friend ostream& operator << (ostream &out, Base<T> *e);
};

template <typename T>
ostream& operator<< (ostream &out, Base<T> *e) {
    out << e->data;
return out;
}

I've read elsewhere online that putting <> between << and () in the prototype should fix this, but it doesn't. Can I get this into a single function template?


Source: (StackOverflow)

clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom)

Why does C++ have public members that anyone can call and friend declarations that expose all private members to given foreign classes or methods but offer no syntax to expose particular members to given callers?

I want to express interfaces with some routines to be invoked only by known callers without having to give those callers complete access to all privates, which feels like a reasonable thing to want. The best I could come up with myself (below) and suggestions by others so far revolve around idioms/pattern of varying indirectness, where I really just want a way to have single, simple class definitions that explicitly indicate what callers (more granularly than me, my children, or absolutely anybody) can access which members. What is the best way to express the concept below?

// Can I grant Y::usesX(...) selective X::restricted(...) access more cleanly?
void Y::usesX(int n, X *x, int m) {
  X::AttorneyY::restricted(*x, n);
}

struct X {
  class AttorneyY;          // Proxies restricted state to part or all of Y.
private:
  void restricted(int);     // Something preferably selectively available.
  friend class AttorneyY;   // Give trusted member class private access.
  int personal_;            // Truly private state ...
};

// Single abstract permission.  Can add more friends or forwards.
class X::AttorneyY {
  friend void Y::usesX(int, X *, int);
  inline static void restricted(X &x, int n) { x.restricted(n); }
};

I'm nowhere near being a software organization guru, but it feels like interface simplicity and the principle of least privilege are directly at odds in this aspect of the language. A clearer example for my desire might be a Person class with declared methods like takePill(Medicine *) tellTheTruth() and forfeitDollars(unsigned int) that only Physician, Judge, or TaxMan instances/member methods, respectively, should even consider invoking. Needing one-time proxy or interface classes for each major interface aspect sits ill with me, but please speak up if you know I'm missing something.

Answer accepted from Drew Hall: Dr Dobbs - Friendship and the Attorney-Client Idiom

The code above originally called the wrapper class 'Proxy' instead of 'Attorney' and used pointers instead of references but was otherwise equivalent to what Drew found, which I then deemed the best generally known solution. (Not to pat myself on the back too hard...) I also changed the signature of 'restricted' to demonstrate parameter forwarding. The overall cost of this idiom is one class and one friend declaration per permission set, one friend declaration per set approved caller, and one forwarding wrapper per exposed method per permission set. Most of the better discussion below revolves around the forwarding call boilerplate that a very similar 'Key' idiom avoids at the expense of less direct protection.


Source: (StackOverflow)

Why does a C++ friend class need a forward declaration only in other namespaces?

Suppose I have a class F that should be friend to the classes G (in the global namespace) and C (in namespace A).

  • to be friend to A::C, F must be forward declared.
  • to be friend to G, no forward declaration of F is necessary.
  • likewise, a class A::BF can be friend to A::C without forward declaration

The following code illustrates this and compiles with GCC 4.5, VC++ 10 and at least with one other compiler.

class G {
    friend class F;
    int g;
};

// without this forward declaration, F can't be friend to A::C
class F;

namespace A {

class C {
    friend class ::F;
    friend class BF;
    int c;
};

class BF {
public:
    BF() { c.c = 2; }
private:
    C c;
};

} // namespace A

class F {
public:
    F() { g.g = 3; c.c = 2; }
private:
    G g;
    A::C c;
};

int main()
{
    F f;
}

To me this seems inconsistent. Is there a reason for this or is it just a design decision of the standard?


Source: (StackOverflow)

What is wrong with making a unit test a friend of the class it is testing?

In c++; I have often made a unit test class a friend of the class I am testing. I do this because I sometimes feel the need to write a unit test for a private method, or maybe I want access to some private member so I can more easly setup the state of the object so I can test it. To me this helps perserve encapsulation and abstraction because I am not modifying the public or protected interface of the class.

If I buy a third party library, I wouldn't want it's public interface to be polluted with a bunch of public methods I don't need to know about simply because the vendor wanted to unit test!

Nor do I want have to worry about a bunch of protected members that I don't need to know about if I am inheriting from a class.

That is why I say it preserves abstraction and encapsulation.

At my new job they frown against using friend classes even for unit tests. They say because the class should not "know" anything about the tests and that you do not want tight coupling of the class and its test.

Can someone please explain these reasons to me more so that I may understand better? I just do not see why using a friend for unit tests is bad.


Source: (StackOverflow)

When to use friend class in C++ [duplicate]

Possible Duplicate:
When should you use 'friend' in C++?

I was brushing up on my C++ (I'm a Java developer) and I came across the friend class keyword which I had forgotten about for a while. Is this one of those features that's just part of the kitchen sink, or is there a good reason for doing this rather than just a vanilla getter? I understand the difference in that it limits who can access the data, but I can't think of a scenario when this would be necessary.

Note: I've seen a similar question, but specifically I'm asking, is this just an advanced feature that adds no real value except to confuse people looking at you're code until they realize what you're doing?


Source: (StackOverflow)

public friend swap member function

In the beautiful answer to the copy-and-swap-idiom there is a piece of code I need a bit of help:

class dumb_array
{
public:
    // ...
    friend void swap(dumb_array& first, dumb_array& second) // nothrow
    {
        using std::swap; 
        swap(first.mSize, second.mSize); 
        swap(first.mArray, second.mArray);
    }
    // ...
};

and he adds a note

There are other claims that we should specialize std::swap for our type, provide an in-class swap along-side a free-function swap, etc. But this is all unnecessary: any proper use of swap will be through an unqualified call, and our function will be found through ADL. One function will do.

With friend I am a bit on "unfriendly" terms, I must admit. So, my main questions are:

  • looks like a free function, but its inside the class body?
  • why isn't this swap static? It obviously doesn't use any member variables.
  • "Any proper use of swap will find out swap via ADL"? ADL will search the namespaces, right? But does it also look inside classes? Or is here where friend comes in?

Side-questions:

  • With C++11, should I mark my swaps with noexcept?
  • With C++11 and its range-for, should I place friend iter begin() and friend iter end() the same way inside the class? I think the friend is not needed here, right?

Source: (StackOverflow)

Are inner classes in C++ automatically friends?

If I define an inner class in C++, is it automatically a friend of the class that contains it? For example, is this legal:

class Outer {
public:
    class Inner {
    public:
        void mutateOuter(Outer& o);
    };

private:
    int value;
};

void Outer::Inner::mutateOuter(Outer& o) {
    o.value ++; // Legal?  Or not?
}

I ask because on some compilers I've tried (VS2003) this code won't work, but I've heard at least anecdotally that it does work on some compilers. I can't find a relevant section in the C++ spec about this, and if anyone can cite something specific that would say that it is or is not legal that would be great.


Source: (StackOverflow)