Default Constructor

  • If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. If the class is abstract then the declared accessibility for the default constructor is protected. Otherwise, the declared accessibility for the default constructor is public. Thus, the default constructor is always of the for

  • these are 2 types
  • User Defined Default Constructor
  • User Defined Default Constructor


    Program of user default Constructor
    using System;
    using System.Collection.Generic;
    using System.Linq;
    using System.Text;
    namespace OOP {
    	class ClsEmp {
    		int EmpId ,EAge ;
    		string EName,EAdd;
    		public ClsEmp() {
    			this.EmpId=101;
    			this.EName=”Scanftree”;
    			this.EAdd=”UP”;
    			this.EAge=24;
    		}
    		public void DisplayEmpData() {
    			Console.WriteLine(“Emp Id is :”+EmpId);
    			Console.WriteLine(“Emp Name is :”+EmpName);
    			Console.WriteLine(“Emp Add is :”+EmpAdd);
    			Console.WriteLine(“Emp Age is :”+EmpAge);
    		}
    		static void Main() {
    			ClsEmp obj=new ClsEmp();
    			obj.DisplayEmpData();
    			Console.WriteLine();
    		}
    	}
    }
    

    System Defined Default Constructor

  • This types of Constructor does not take parameter .
  • Constructor without any parameter is called a default constructor
  • Drawback is this Constructor is that every instance of the class will be initialized to the same value and it is not possible to initialize each instance of the class to the different values .

  • Program System Defined Default Constructor

     using System;
    using System.Collection.Generic;
    using System.Linq;
    using System.Text;
    namespace OOP {
    	class ClsEmployee {
    		int EmpId ,EAge ;
    		string EName,EAdd;
    		public void DisplayEmpData() {
    			Console.WriteLine(“Emp Id is :”+EmpId);
    			Console.WriteLine(“Emp Name is :”+EmpName);
    			Console.WriteLine(“Emp Add is :”+EmpAdd);
    			Console.WriteLine(“Emp Age is :”+EmpAge);
    		}
    		static void Main() {
    			ClsEmployee obj=new ClsEmp();
    			obj.DisplayEmpData();
    			Console.WriteLine();
    		}
    	}
    }