A parameterized constructor that contains a parameter of itself is called as Copy Constructor. The objective of this constructor is to initialize the new instance with existing one.
Let’s explain this with an example here:
class A
{
public string Val;
public A(string strVal)
{
Val = strVal;
}
//This is example of copy constructor.
public A(A objA)
{
Val = objA.Val;
}
}
static void Main(string[] args)
{
A objA = new A("Oops");
A objAC = new A(objA);//All objA details will be copied to objAC
Console.WriteLine("Value of objAC object == "+ objAC.Val);
Console.ReadLine();
}
Output of this program would be
This example clearly explains what is the role of copy constructor. It can be very handy in certain situation.
No comments:
Post a Comment