Pages

Saturday 12 January 2013

Constructor and Destructor

Constructors and Destructors:

Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
  • 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 const, or volatile.
  • Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.
The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.

Example of Constructor

class C
{
       private int x;    
       private int y;
       public C (int i, int j)
       {
                 x = i;
                 y = j;
       }
       public void display ()     
       {
               Console.WriteLine(x + "i+" + y);
       }
}

Example of Destructor

class D
{
        public D ()
        {
            // constructor
        }         
        ~D ()
        {
           // Destructor
        }
}

No comments:

Post a Comment