C++ class consturctor

A constructor is a "special" member function which initialize the objects of class.

Properties of constructor :

          Constructor is invoked automatically whenever an object of class is created. Constructor name must be same as class name.
          Constructor do not have return types and they cannot return values, not even void. They make implicit calls to the operators new and delete when memory allocation is required.

          Constructor should be declared in the public section because private constructor cannot be invoked outside the so they are useless.

          Constructor do not have return types and they cannot return values, not even void and it cannot be inherited, even through a derived class can call the base class constructor.

          An object with a constructor cannot be used as a member of a union and it cannot be virtual.   
          There are mainly three types of constructor as follows:
  • Default constructor,
  • Copy constructor,
  • Parameterized constructor 

* Default constructor :  

                        Default constructor is the one which invokes by default when object of the class is created. It is generally used to initialize the value of the data members. It also called no argument constructor. 

Example :

class integer
{
            int m,n;
            public:
                   integer()          // Default constructor
                  {
                        m=n=0;
                  }
};

* Parameterized constructor :

                      Constructors that can take arguments are called parameterized constructors. Sometimes it is necessary to initialize the various data elements of different objects with different values when they are created. We can achieve this objective by passing arguments to the constructor function when the objects are created.

Example :

class integer
{
            int m,n;
            public:
                   integer(int x, int y)          // Parameterized constructor
                  {
                        m=x;
                        n=y;
                  }
};

* Copy constructor :

                     A copy constructor  is used to declare and initialize an object from another object. Constructor which accepts a reference to its own class as a parameter is called copy constructor.

For example, integer(integer &i); OR integer I2( I1 );

Example :

class integer
{
            int m,n;
            public:
                   integer(rectangle &x)          // Parameterized constructor
                  {
                        m=x.m;
                        n=x.n;
                  }
};