views:

229

answers:

1

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?

+1  A: 

It seems that this idiom like one mentioned in another SO question here. It is called Attorney-Client idiom and described in more details there.

Haspemulator
I already linked to another answer to that question and the pattern above doesn't involve proxying through another class. There is no *"attorney"* we need to call through (they are expensive anyway), instead we simply get access by passing a *key* along.
Georg Fritzsche
@Georg: In what real sense are the attorney calls expensive? If they are stateless, static inlines that merely forward arguments, how would any size or time penalty be introduced?
Jeff
@jeff: The point on expenses was meant to be a pun regarding hourly rates ;) Still, one has to manually forward in the attorney case - you have to write more.
Georg Fritzsche
@Georg: sorry, read pun as double entente on the _call_ expense, not on method _definition_. I generally agree, but I did make a comment in the other question's thread about actual runtime expense.
Jeff