Copy Constructor
- Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type.
- The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
- The copy constructor is used to:
- Initialize one object from another of the same type.
- Copy an object to pass it as an argument to a function.
- Copy an object to return it from a function.
- If a copy constructor is not defined in a class, the compiler itself defines one.
- the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor.
- it is usually of the form X (X&), where X is the class name.he compiler provides a default Copy Constructor to all the classes.
Syntax:
classname (const classname &obj) {
// body of constructor
}
Here, obj is a reference to an object that is being 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<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}
Output:
Im Constructor
Values :10 20
Values :10 20
Ask Question