Object Oriented Design help from C++ to C#

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
{
    friend 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

    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.

Answers


The goal here seems to be that you cannot have a CFoo until you have a working CBar.

You could achieve the same with C# by having a private constructor for CFoo and then making a static method in CFoo that takes a CBar argument and calls said constructor and returns the new CFoo.

This would be something like the System.Drawing.Graphics.FromImage(Image image) method.

The question of why C# doesn't have the friend keyword has been covered elsewhere.


Need Your Help

Click a div to check / uncheck a checkbox

jquery

I applied the following code to make table rows check/uncheck a child checkbox when clicked. Now I discovered that when clicking the checkbox itself inside the row it doesent check. Could it be tha...

Cannot import urllib.request and urllib.parse

python import import-libraries

I will be grateful for any help. I use Python 3.4.1 and I try to import urllib.request and urllib.parse. Without success. I always receive:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.