Friday, 26 August 2011

Private Constructor


When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern.

If you declare a Constructor as private then it doesn't allow to create object for its
derived class, i.e you loose inherent facility for that class.

In the following program I'm trying to create a derived class  for the Base class having Private constructor it shows an error like .
   Error: parent()  is inaccessible due to its protection level   
Use public instead of private then  the following program works...



class parent
    {
       public  string name;
       private   parent()
       //use public instead of private then this program works...
        {
            this.name = "Radha";
        }
    }

    class child : parent
    {
        public void show()
        {
            Console.WriteLine(name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            child obj = new child();
            obj.show();
            Console.Read();

        }
    }
}


// Error :: parent()' is inaccessible due to its protection level  

No comments:

Post a Comment