CPP

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:
  1. Initialize one object from another of the same type.
  2. Copy an object to pass it as an argument to a function.
  3. 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



Subscribe us on Youtube

Share This Page on

Questions


clinto thomas | 18-Apr-2017 08:58:00 pm

The examaple shown above is wrong . in this exaple he is simply using the overloaded = operatoe to copy from one object to another .


Admin Vikesh | 05-May-2017 12:47:17 pm

Hello, clinto thomas Thank you for giving your valuable feedback. Can you provide correct example? Team Tutorialink


Ask Question