Constructor is a function for object initialization. All classes has a default constructor base which will be called
if there is not constructor provided.
Constructors are usually has the same name as the class and do not return values.
class human { public int age; public human() { ... } }
class weekdays { private weekdays() {}; public static string[] arr = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"}; public static showweekday(int i) { i -= 1; if (i < 0 && i > 6) return "NA"; return arr[i]; } } weekdays d = new weekdays(); //error weekdays.showweekday(2); //Tuesday
class human { public int age; public string sex; public string race; public human() { sex = "unknown"; age = 0; race = "unknown"; } public human(int a,string s) { sex = s; age = a; race = "unknown"; } public human(int a,string s,string r) { sex = s; age = a; race = r; } } human h = new human(); //OK h.age; //0 h.race; //unknown human h2 = new human(28,"James"); //OK h2.age; //28 h2.race; //unknown human h3 = new human(28,"James","English"); //OK h3.age; //28 h3.race; //English
class human { public int age; public human() { ... } public ~human() //destructor { ... } }