What is copy constructor?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 <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Student
{
public:
Student()
{
cout << "Default constructor\r\n";
}
Student(int nAge)
{
cout<<"Overloaded Constructor Called \r\n";
m_nAge=nAge;
}
Student(Student &a)
{
cout << "Copy constructor\r\n";
m_nAge = a.m_nAge;
}
int m_nAge;
};
int main()
{
Student obj(13);
cout<<"Age: "<< obj.m_nAge<<"\r\n";
Student obj1(obj);
cout<<"Age: "<<obj1.m_nAge<<"\r\n";
getch();
return 0;
}
Result:
Overloaded Constructor Called
Age: 13
Copy constructor
Age: 13