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