Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grant access to private constructor without friends?

I am working on some code, where I encountered a situation similar to this one:

struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

like image 692
463035818_is_not_a_number Avatar asked Mar 29 '17 06:03

463035818_is_not_a_number


1 Answers

This is precisely what the attorney-client idiom is for:

struct Bar;

struct Foo {
    friend struct FooAttorney;
private:
    Foo(){}
    void f(){}
    void g(){}
};

class FooAttorney {
  static Foo* makeFoo() { return new Foo; }
  friend struct Bar;
};

struct Bar {
   Foo* f;
   Bar()  { f = FooAttorney::makeFoo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

In a code imitates life fashion, the class declares an attorney that will mediate the secrets it's willing to share with the selected parties.

like image 132
StoryTeller - Unslander Monica Avatar answered Nov 20 '22 07:11

StoryTeller - Unslander Monica