Constructors

A constructor is a special kind of member function wich initializes objects of a class. It is different from a normal member function in many ways:

1. A constructor's name must be same as the class name with which it is associated.

2. It is called automatically when an object of the class is created.

3. It has no return type.

4. It must be specified as Public access specifier. 


Syntax:

class class_name

{

  public:

  class_name     //constructor name, same as the class name

  {

    ...

   }

};


Example:

//a simple C++ program to demonstrate constructors

#include<iostream.h>

#include<conio.h>

using namespace std;

class Example

{

  int a;          // Variable Declaration

  public:

  Example()           //Constructor

  {

      a = 15;        // assigning value in constructor

      cout << "Value of a is: "<<a;

   }

};

int main() 

{

   Example Obj;        //constructor automatically called

   return 0;

}

OUTPUT:



Types of constructors


1. Default constructors: They have no parameters. A default constructor essentially initializes objects of the class such that even if it is not defined explicitely in the class,a default constructor with an empty body is implicitely provided by the compiler.

Example 1:

//C++ program to demonstrate default constructors

#include<iostream.h>

#include<conio.h>

using namespace std;

class fun

{

  public:

  fun();       //constructor declaration

};

fun::fun()         //constructor definition

{

   cout<<" This is an example of Default Constructor. ";

}

int main()

{

  fun obj;        //creating object

  return 0;

}

OUTPUT:



Example 2:

//C++ program to demonstrate default constructor without defining it

#include<iostream.h>

#include<conio.h>

using namespace std;

class square

{

  public:

  int area;

};

int main()

{

  square ar;

  cout<< ar.area;

  return 0;

}

OUTPUT:



In the above example, square class has no constructor. Compiler implicitely generates a public default constructor though it is not visible to us.


2. Parameterized Constructors: We can also declare constructors with parameters ( called as parameterized constructors).


Example:

//C++ program to demonstrate parameterized constructor

#include<iostream.h>

#include<conio.h>

using namespace std;

class  para

{

  public:

  int A, B, C;    //variable declaration

  para(int a, int b, int c)        //parameterized constructor

  {

     A=a;       

     B=b;

     C=c;

     cout<<"The value of a: "<<A<<endl;

     cout<<"The value of b: "<<B<<endl;

     cout<<"The value of c: "<<C<<endl;

  }

};

int main()

{

  para val(1, 2, 3);       //constructor called

  return 0;

}


OUTPUT:



3. Copy Constructor: It initializes an object by using another object of same class.

Syntax:

class class_name

{

  class_name(const class_name &object_name)

  {

     //copy constructor

  }

}

Let's have a look on the below example to understand the concept of copy constructor.

Example:

//C++ program to demonstrate copy constructor

#include<iostream.h>

#include<conio.h>

using namespace std;

class val

{

  public:

  int a, b;

  val(int x, int y)    //normal contructor

  {

     a=x;

     b=y;

  }

  val(const val &obj1)     //copy constructor

  {

     a= obj1.a;

     b= obj1.b;

  }

  int showA()

  {

     return a;

  }

  int showB()

  {

     return b;

  }

};

int main()

{

  val obj2(15,30);       //normal constructor called

  val obj1= obj2;          //copy constructor called

  cout<<"Value of a: "<<obj2.showA();

  cout<<"\nValue of b: "<<obj1.showB();

  return 0;

}

OUTPUT:



Constructors overloading


When more than one constructor is used in the same class, it is said to be constructor overloading (also know as multiple constructor).

Some essential points must be kept in mind while using multiple constructors:

i. Overloaded constructors must have different number of arguments.

ii. Calling of the constructor depends on the number and types of arguments passed.

iii. There are as many objects created as the number of constructors. 

iv. Arguments must be passed while creating objects so that the compiler could know the respective constructor, to be called.


Example:

//C++ program to demonstrate constructor overloading

#include<iostream.h>

#include<conio.h>

using namespace std;

class volume

{

public:

  volume()              //constructor without any parameter

  {

     cout << "Here's the volume of different geometrical shapes- " << endl;

  }

  volume(int a)            //constructor with one parameter

  {

     cout << "Volume of the cube = " << a * a * a << endl;

  } 

  volume(int r, int h)             //constructor with two parameters

  {

     cout<< "Volume of the cone is: "<< 0.3 * 3.14 * r * r * h << endl;

  }

  volume(int l, int b, int h)               //constructor with three parameters

  {

     cout << "Volume of the cuboid is: " << l * b * h << endl;

  }

};

int main()

{

   volume object1;

   volume object2(3); 

   volume object3(3, 4);    

   volume object4(3, 4, 5);

   return (0);

}

OUTPUT:



Constructors with default arguments

In this, the constructor is passed with arguments which have default values. These default values can be changed when the constructor will be called in the main function, according to the requirement. Otherwise, the constructor with default arguments gets called when the object is created.

To understand this concept of constructor with default arguments, let's consider an example.

Example:

//C++ program to demonstrate default arguments

#include<iostream.h>

#include<conio.h>

using namespace std;

class example

{

  public:

  example(int a= 5, int b=10)        //constructor with default arguments     

  {

     int p= a*b;

     cout<<"Product of a and b= "<<p<<endl;

  }

};

int main()

{

  example obj;          //constructor with default arguments is called

  example obj1(2);       //example(2, 10) is called

  example obj2(3,5);         //example(3, 5) is called

  return 0;

}

OUTPUT:


Destructors

A destructor is opposite to a constructor. Its name is same as the class name prefixed with a tidle (~) sign. It is an other kind of member function which destroys (or deletes) an object. It is automatically called when the object goes out of scope i.e. when the function, the program and blocks containing local variables end, and when a delete operator is called.


Here is a simple example for the better understanding of destructor.

Example:

//C++ program to demonstrate destructor

#include<iostream.h>

#include<conio.h>

#include<string.h>

using namespace std;

class destruc

{

  public:

  string obj;

  destruc()       //constructor definition

  {

     obj= "Item";

     cout<<"An object is created: "<<endl<<obj;

  }

   ~destruc()           //destructor definition

  {

     cout<<"\n\nThe object has been destroyed."<<endl;

  }

};

int main()

{

   destruc d1;           //constructor and destructor automatically called

   return 0;

}

OUTPUT:




Uses: 

Destructors are used to deallocate memory. They free the resources which might have been acquired by the object during its lifetime. They do  other cleanup for a class object and the data members when the object is dectroyed.

Note: If you don't know what Arguments is, we suggest that you read our Arguments and static function in oop tutorial