Copy Constructor in C++ with example



Copy Constructor is always used when the compiler has to create a temporary object of a class object. The Copy Constructor is used in
1.      When the initialization of an object by another object of the same class.
2.      Return of objects as a function value.
3.      When stating the objects as by value parameters of a function.

Example:
#include<iostream.h>
#include<conio.h>
Class employee
               {
               int id;
               char name[20];
               public:
               employee (int t)
                              {
                              id = t;
                              }
               employee (employee &t)
                              {
id=t.id;
                              strcpy (n, t.n);
                              }
void get();
void put();           
};
void employee :: get()
{
cout<<”Enter the employee name =”;
cin>>name;    
}
void employee :: put()
{
               cout<<” Employee Id = ”<<id;
               cout<<” Employee Name = ”<<name;
}
void main()
{
clrscr();
               employee emp(110);
               emp.get();
               emp.put();
em(111);
               em.get();
               em.put();
               getch();
}

No comments:

Post a Comment