ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,jQuery Plugins,jQuery UI,SSRS,XML,HTML,jQuery demos,code snippet examples.

Breaking News

  1. Home
  2. OOPs
  3. Constructor and Destructor

Constructor and Destructor

Constructor
Constructor is a member function and its name is as like as class name. It is used to initialize the class object. Constructor & Destructor both are necessary for every class. If we don’t create them compiler automatically create them by himself. Constructor & Destructor has no return type. It is called when a class object is created. Constructor & Destructor has no statement primarily. But we can create custom statement. Constructor may have parameter or not.
Example:
ClassName(Arguments)
{
//Body of Constructor
}

Types of Constructor
There are three types of constructor
  1. Default Constructor – It does not take any parameter.
  2. Parameterized Constructor – It accept parameters.
  3. Copy Constructor – A Special type of constructor which takes an object as argument. It is used to copy values of data member of one object into other object.

Destructor
Destructor is used to delete object instance from the memory. We need to destroy object instance after its task. If we don’t does this compiler automatically do this? Its name is as like class name. Only extra ~ sign is used before its name. It has no parameter and it doesn’t accept any operator.
Example:
~ClassName()
{
}

The following limitations apply to constructors and destructors:
  • Constructors and destructors do not have return types nor can they return values.
  • References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
  • Constructors cannot be declared with the keyword virtual.
  • Constructors and destructors cannot be declared static, const, or volatile.
  • Unions cannot contain class objects that have constructors or destructors.

Difference between Constructor and Destructor
Constructor
Destructor
It is used to initialize the instance of a class.It is used to destroy the instance of a class.
It is called when new instance of a class is created.It called when instance of a class is deleted.
It allocates the memory.It releases the memory.
It may have parameter or not.It has no parameter.
Overloading is possibleOverloading is not possible.
Its name is as like class name.Its name is as like class name but with (~) tiled operator.

No comments