Opposite of friend declaration

  • A+
Category:Languages

Say we have a class that has a private constructor, through friend we can allow some specific class(es) to still create objects of this class:

class Foo {  friend class Bar; private:   Foo(); };  class Bar {   Bar()   {     //create a Foo object   } }; 

Now what if I want the opposite of friend, where Foo looks like this:

class Foo {  //enemy/foe??? class Bar; (if only) public:   Foo(); }; 

And then no method of Bar can access the Foo constructor/ make an object of Foo but other classes can (because it's public).

class Bar {   Bar()   {     Foo foo; //compiler error   } }; 

Is such a construct possible or am I stuck with keeping Foo private and adding friends for all the classes?

 


Such a thing does not exist, and it would be extremely pointless. Imagine you have a situation like this:

class Foo {   enemy class Bar;  public:   Foo() {} };  class Bar {   void evil() { Foo{}; } }; 

Nothing prevents the implementor of Bar from doing this:

class Bar {   void evil() { do_evil(*this); } };  void do_evil(Bar &self) {   Foo{}; } 

do_evil is not a member of Bar (it's a global function), and so it's not an enemy. Such non-friendliness could therefore be trivially circumvented.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: