The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Constructors and Destructors

Constructors
A constructor is a special member function of a class with the same name as that of the class and it is invoked whenever an object is created. It doesn't have any return type. Every class must have atleast one constructor. You must have observed that in the previous section on Classes and Objects, we have written programs in which there are classes without constructor. The fact is that if we don't define a constructor, compiler automatically generates a default constructor. Constructors are used to initialize the data members of a class. Any number of constructors can be defined for a class and constructors can take arguments also like a normal function. See the program below :

#include<iostream>
using namespace std;

class rectangle {
   int length, breadth;
public :
   rectangle() { } // default constructor
   rectangle(int l, int b) { // parametrized constructor
      /* dimensions can be initialized here */
      length = l;
      breadth = b;
   }
   void setDimensions(int l, int b) {
      /* dimensions can be initialized here also */
      length = l;
      breadth = b;
   }
   void printArea() {
      int area = length * breadth;
      cout << "Area : " << area << endl;
   }
};

int main() {
   rectangle rect1; // default constructor is invoked
   rect1.setDimensions(6, 7); // set the rectangle dimensions
   rect1.printArea(); // display the area of rectangle
   rectangle rect2(5, 9); // parametrized constructor is invoked
   rect2.printArea();
   return 0;
}

Note :
1 ) If no constructor is defined, it's fine. We can create objects since default constructor is automatically defined by compiler but it is a good practice to define a default constructor.
2 ) If you define a parameterized constructor then, a default constructor must be defined manually otherwise a statement like " rectangle rect; " which invokes default constructor would give a compilation error.
3 ) Like any other member function, a constructor can be defined inside or outside the class.
4 ) Multiple constructors in a class with different types and number of arguments is known as constructor overloading. This is just a jargon. You can peacefully forget it.

Initialization list in Constructor
Initialization lists can be used to initialize the data members in constructors. Following program illustrates the use of initialization list :

#include<iostream>
using namespace std;

class rectangle {
   int length, breadth;
public :
   rectangle() { }
   // constructor with initialization list
   rectangle(int l, int b) : length(l), breadth(b) { }
   void printArea() {
      int area = length * breadth;
      cout << "Area : " << area << endl;
   }
};

int main() {
   rectangle rect2(6, 4);
   rect2.printArea();
   return 0;
}


Copy Constructor
A copy constructor is used to create an object and initialize it with another object of the same class. Initializing an object simply means initializing its data members. A copy constructor takes an object of the same class as an argument. See the program below :

#include<iostream>
using namespace std;

class rectangle {
   int length, breadth;
public :
   rectangle() { }
   rectangle(int l, int b); // constructor declared not defined
   rectangle(rectangle &rect); // copy constructor declared    
   void printArea();
};

// define the parameterized constructor
rectangle :: rectangle(int l, int b) {
   length = l;
   breadth = b;
}

// define the copy constructor
rectangle :: rectangle(rectangle &rect) {
   length = rect.length;
   breadth = rect.breadth;
}

// print Area of rectangle
void rectangle :: printArea() {
   int area = length * breadth;
   cout << "Area : " << area << endl;
}

int main() {
   rectangle rect1(6, 4); // create an object rect1 
   rect1.printArea();
   /* create an object rect2 and initialize it with rect 1
      rect2.length = rect1.length and rect2.breadth = rect2.breadth */
   rectangle rect2(rect1);
   rect2.printArea();
   return 0;
}


Destructors
A destructor is a special member function with the same name as that of the class but preceded by a tilde ( ~ ) sign. It is used to destroy an object when the object goes out of scope or it is deleted. A destructor neither takes any argument nor does it returns anything. It is used for releasing resources used by the object like freeing the memory allocated for a data member during creation of an object. Destructor is invoked automatically by the compiler. Following program illustrates the use of destructor :

#include<iostream>
#include<cstring>
using namespace std;

class employee {
   int id;
   char *name;
public :
   employee() { }
   employee(int e_id, char e_name[], int size) {
      id = e_id;
      name = new char[size]; // dynamically allocating memory
      strcpy(name, e_name);
      cout << "Object Created" << endl;
   }
   void displayInfo() {
      cout << "ID : " << id << " ";
      cout << "Name : " << name << endl;
   }
   ~employee() { // destructor
      delete name; // frees the allocated memory
      cout << "Object Destroyed" << endl;
   }
};

int main() {
   int id = 101;
   char name[] = "John";
   int size = 4; // size of the array 'name'
   employee emp(id, name, size);
   emp.displayInfo();
   return 0;
}

Back | Next