homer512 icon

private ctor factory

homer512 | PRO | 07/04/14 04:08:29 PM UTC | 0 ⭐ | 772 👁️ | Never ⏰ | []
C++ |

830 B

|

None

|

0 👍

/

0 👎

namespace {
 
  class Factory;
 
  class FactoryKey
  {
    friend class Factory;
  private:
    /* Only Factory can build one */
    FactoryKey() {}
    /* Prevent "stealing" a key by copying it */
    FactoryKey(const FactoryKey&);
  };
 
  class Base
  {
  protected:
    /* Prevent construction by anyone who cannot provide a FactoryKey */
    Base(const FactoryKey&) {}
  public:
    virtual ~Base() {}
  };
 
  class Derived: public Base
  {
  public:
    Derived(const FactoryKey& key)
      : Base(key)
    {}
    virtual ~Derived() {}
  };
 
  class Factory
  {
  public:
    template<class T>
    T* build()
    {
      return new T(FactoryKey());
    }
  };
 
}
 
int main()
{
  Factory fact;
  fact.build<Derived>();
  new Derived(FactoryKey()); /* <--- error: FactoryKey() is private here */
}

Comments