CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2008
    Posts
    23

    Can we create object of class with private constructor?

    Hi,
    Can we create an object of a class having private constructor. If so, then how? Please tell me.
    Thanks in advance

  2. #2
    Join Date
    Oct 2005
    Location
    Seattle, WA U.S.A.
    Posts
    353

    Re: Can we create object of class with private constructor?

    I would think that if the constructor is private, then no non-member could access the constructor. However, class members including static members would still be able to do so.

    so one might build a class such as the following...
    Code:
        public partial class xyz {
            public string abc;
            public int number;
    
            private xyz() {
                abc = "this is a public string";
                number = 7;
            }
    
            public static xyz pleaseConstructAnObjectForMe() {
                return new xyz();
            }// end function 'pleaseConstructAnObjectForMe'
    
        }// end this segment, class 'xyz' partial declaration
    and call it as follows ...
    Code:
    //            xyz pXYZ = new xyz(); // doesn't compile!
    
                xyz pXYZ = xyz.pleaseConstructAnObjectForMe();
                MessageBox.Show(pXYZ.abc);
    indeed, I may be mistaken, but I seem to recall seeing instances in the .NET Framework where classes couldn't be constructed other than by referencing a static function.

    OldFool

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured