A constructor is a “special” member function which initializes the objects of class.

Properties of constructor:

Constructor is invoked automatically whenever an object of class i s created.

Constructor name must be same as class name.

Constructors should be declared in the public section because private

constructor cannot be invoked

outside the class so they are useless.

Constructors do not have return types and they cannot return values, not even void.

Constructors cannot be inherited, even though a derived class can call the base class constructor.

Constructors cannot be virtual.

An object with a constructor cannot be used as a member of a union.

They make implicit calls to the operators

new

and

delete

when memory allocation is required.

* Copy Constructor

 

A copy constructor is used to declare and initialize an object from another object

.For example,

integer(integer &i);

OR

integer I2(I1);

Constructor which accepts a reference to its own class as a parameter is called cop

y constructor.

Example:

class integer

{

int m, n;

public:

integer(rectangle &x) // Copy constructor

{

m = x.m;

n = x.n ;

}

};

Example:

#include<iostream>

using namespace std;

class rectangle

{

int length, width;

public:

rectangle() // Default constructor

{

length=0;

width=0;

}

rectangle(int _length, int _width) // Parameterized constructor

{

length = _length;

width = _width;

}

rectangle(rectangle &_r) // Copy constructor

{

length = _r.length;

width = _r.width;

}

....................................

// other functions for reading, writing and processing can be written

here

....................................

};

int main()

{

rectangle r1; // Invokes default constructor

rectangle r2(10,10); // Invokes parameterized constructor

rectangle r3(r2); // Invokes copy constructor

}