In C++, Copy Constructor is a type of constructor that is typically used to create a copy of an already existing object of a class type. It is a constructor that creates an object by initializing it with an object of the same class, that was previously created.
You can copy the constructor to do the following:
The compiler can define a copy constructor in a class if the copy constructor was not initially defined. This because the class has pointer variables and has some dynamic memory allocations, and as such, it is must have a copy constructor.
Below is the general form of a copy constructor:
Syntax:
classname (const classname &obj) {
// body of constructor
}
From the syntax above, obj is a reference to any object that is used to initialize another object.
Example:
#include<iostream.h>
#include<conio.h>
class copy
{
int var,fact;
public:
copy(int temp)
{
var = temp;
}
double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
{
clrscr();
int n;
cout<<"ntEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"nt"<<n<<" Factorial is:"<<obj.calculate();
cout<<"nt"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}