In addition to providing a default constructor and a destructor, the compiler also provides a default copy constructor which is called each time a copy of an object is made. When a program passes an object by value, either into the function or as a function return value, a temporary copy of the object is made. This work is done by the copy constructor.

All copy constructors take one argument or parameter which is the reference to an object of the same class. The default copy constructor copies each data member from the object passed as a parameter to the data member of the new object.

Example:

#include<string.h>
#include<iostream.h>
class number
{
private:
  int n;
  public:
  number(int d)
  {
    n=d;
  }
  number(number &a)
  {
    n = a.n;
    cout << "The copy constructor:";
  }
  void display()
  {
    cout << "The number = " << n;
  }
};
int main (int argc, char *argv[])
{
  number n1(10);
  number n2(n1);/*copy constructor called*/
  cout << "object n1:";
  n1.display();
  cout << "object n2:";
  n2.display();
}

About our authors: Team EQA

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.

#