Hey I usually run into a situation where I will create a class that should only be instantiated by one or a few classes. In this case I would make its constructor private and make it a friend class to the objects that should be able to instantiate it. For example (in C++):
class CFoo
{
// private ctor because only a select few classes should instantiate
private:
CFoo()
{
... Do stuff
}
}
class CBar
{
// CBar is one of the few classes that only need to use CFoo
friend class CFoo;
CFoo *m_pFoo;
CBar()
{
m_pFoo = new CFoo;
}
}
So my question is: Is this stupid? Or is there a better way to achieve this? I'm especially interested in a way where it would work with C# considering the language lacks the friend keyword completely. Thanks.