Constructor Initializer
There are two types of constructor initializer,
- base() - To call the Base Class Constructor
- this() - To call another constructor in this class
Example:
class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base Class Constructor");
}
public BaseClass(int n)
{
Console.WriteLine(n.ToString());
}
}
class DerivedClass:BaseClass
{
//Call the base class constructor and then the current constructor
public DerivedClass()
{
Console.WriteLine("Derived Class Constructor");
}
public DerivedClass()
{
Console.WriteLine("Derived Class Constructor");
}
//Calls base class contructor with one int argument and then current constructor
public DerivedClass(int n):base(10)
{
public DerivedClass(int n):base(10)
{
Console.WriteLine(n.ToString());
}
}
//Calls the single string argument constructor and then the current
public DerivedClass(string firstname,string lastname):this("Bala")
{
Console.Write(firstname+" "+lastname);
}
public DerivedClass(string surname)
{
Console.Write(surname+" ");
}
}
DerivedClass dc1=new DerivedClass();
DerivedClass dc2=new DerivedClass(5);
DerivedClass dc3=new DerivedClass("satheesh","babu");
public DerivedClass(string firstname,string lastname):this("Bala")
{
Console.Write(firstname+" "+lastname);
}
public DerivedClass(string surname)
{
Console.Write(surname+" ");
}
}
DerivedClass dc1=new DerivedClass();
DerivedClass dc2=new DerivedClass(5);
DerivedClass dc3=new DerivedClass("satheesh","babu");
OUTPUT:
Base Class Constructor
Derived Class Constructor
10
5
Base Class Constructor
India Tamil Nadu
Base Class Constructor
Derived Class Constructor
10
5
Base Class Constructor
India Tamil Nadu
public DerivedClass()
is equivalent to,
Note: If there is no constructor for a class then compiler will create a default constructor with no arguments and with no
body.
public DerivedClass():base()
The compiler will take care of it and will call the base class constructor before calling this constructor.Likewise it works for others also.we'll get a compile-time error if we don't provide a constructor initializer and the base class doesn't have an accessible parameterless constructor.
Note: If there is no constructor for a class then compiler will create a default constructor with no arguments and with no
body.



0 Comments:
Post a Comment
<< Home