Constructors are methods of a class which get executed
automatically when an instance of a class is created. The constructor method
name should be same as the class name.
The following example defines a simple constructor for
the class CEmployee
class CEmployee
{
public int id;
public string Name;
//
public CEmployee()
{
}
}
The default constructor does not take any parameters,
and this constructor is called when an object of the class is created without
passing any parameters as follows.
CEmployee objClass1 = new CEmployee();
CEmployee objClass1 = new CEmployee();
A class can have more than one constructor, we can create many overloaded constructors for a class, but no two constructors should have the same signature, they should vary either by the number of parameters or the type of parameters.
The following example defines 2 overloaded constructs for our class CEmployee
class CEmployee
{
public int id;
public string Name;
//
public CEmployee()
{
}
//
public CEmployee(int
nId)
{
this.id = nId;
}
//
public CEmployee(int
nId, string sName)
{
this.id = nId;
this.Name = sName;
}
}
The first constructor takes only one parameter nId and initializes the id member of the class, the 2nd constructor takes two parameters and initializes both the id and name members of the class. Remember that we cannot do this in the case of structs, constructors of a struct should be defined in such a way that it initializes all the members of the class.
The class can be initialized by calling the new overloaded constructor as follows.
CEmployee objClass1 = new CEmployee(1, "Name1");
No comments:
Post a Comment