System Defined Default Constructor



  • If there is no constructor defined within a class then, system will create its own constructor and will assign default values into the Data Fields
  • This constructor created by the system is known as System Defined Default Constructor
  • When an object to the class is created first system will search for a constructor with in the class, If there is no constructor available within the class system will create its own constructor and will assign default values into the Data Fields


Example:-

Class Diagram:-
 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CAConstrucors
{
    class Employee2
    {

        int EmpId, EmpAge;
        string EmpName, EmpDesignation;
        public void DisplayEmpData()
        {
            Console.WriteLine("Employee Id is           " + EmpId);
            Console.WriteLine("Employee Name is         " + EmpName);
            Console.WriteLine("Employee Designation is  " + EmpDesignation);
            Console.WriteLine("Employee Age is          " + EmpAge);
        }

    }
    class SDConstructor
    {
        static void Main()
        {
            Employee2 obj1 = new Employee2();
            Employee2 obj2 = new Employee2();
            obj1.DisplayEmpData();
            obj2.DisplayEmpData();
            Console.ReadLine();
        }

    }
}





Output:-


  • In the above example though we did not write any constructor in the class, default values are stored into the Data Fields. This is because as there is no constructor within the class System Created its own constructor and initialized default values into the Data Fields
Disadvantage of Default Constructor While Initializing The Data
  1. In the above examples, any number of objects we may create for a class, all the objects will store same data in their referenced Data Fields
  2. To overcome this drawback, we use parametrized constructor

No comments:

Post a Comment