Constructors

  • These form the special member functions of the class .
  • These have the same name as class name and constructors do not return any value .
  • A Constructor is complimentary to a destructor. It is a good programming to use both constructors as well as destructors.
  • Constructors can be defined in two ways as
1. static Constructors.
2.Instance Constructors.


Static Constructors:
  • These r used to intialise static variables of a class.
  • These variables r created using static key word and they store values that can be shared by all the instances of a class .
  • Static constructors have an implict private access.
  • These ill be invoked only once during execution.
  • exam:

    public class Example
    {

    static int n1;
    int n2;

    static Example()
    {
    n1=5; /*.................. accepts the value for variable n1............................*/

    n2=10; /.......................... puts an error msg...........*/
    }
    }

note: We use constructors to intialise data members and not for any input or output operations.
and we can have more than one constructor for a class.

Constructors with parameters

At times user wants to pass values to variables at run time where it cant be possible through intializing them at the starting of prog, so during this situation he can make use of passing the values to variables through parameters.
constructors can be used in order to supply values to variables at run time. ......

here is an exam program to illustrate the process of functioning.........

using System;

namespace arithemetic_oper
{
class Addition
{
static int num1,num2;
int total;

Addition(int n1,int n2)
{
num1=n1;
num2=n2;
}

public void addNum()
{
total=num1+num2;
}

public void displayNum()
{
Console.WriteLine(" Result is : {0}",total);
}

public static void Main(String [] arg)
{
int var1,var2;
Console.WriteLine("Enter the var1:\t");
var1= Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the var2:\t");
var2=Convert.ToInt32(Console.ReadLine());

Addition obj=new Addition(var1,var2);

obj.addNum();
obj.displayNum();
Console.ReadLine();
}
}
}

Instance Constructors:

  • Instance constructor is called when ever instance of a class is created.
  • These r used to intialize data members of the class.
  • Constructors do not return any values.
  • If there r no constructors for a class, then compiler creates a default constructor for itself.



0 Comments:

Post a Comment



Newer Post Older Post Home