Copy Constuctor

Copy Constuctor:

It is used to initialized object by using data of another object of same type.its automatically called when object is assigned to it.the reference of the object which is assigned comes as argument to copy contructor.

Example 1

#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 s;

cout<<“\n\tEnter the Number : “;

cin>>s; copy obj(m);

copy cpy=obj;

cout<<“\n\t”<<s<<” Factorial is:”<<obj.calculate();

cout<<“\n\t”<<s<<” Factorial is:”<<cpy.calculate();

getch();

}

Output
Enter the number: 6

6 factorial is:720

6 factorial is:720

Example 2
#include <iostream.h>

#include<conio.h>

using namespace std;

class Example

{

// Variable Declaration

int a1,b1;

public: //Constructor with Argument

Example(int x,int y)

{

// Assign Values In Constructor a1=x; b1=y;

cout<<“\nIm Constructor”;

}

void Display_d()

{

cout<<“\nValues :”<<a1<<“\t”<<b1;

}

};

int main()

{

Example Object(10,20); //Copy Constructor Example Object_2=Object; // Constructor invoked.

Object.Display_d();

Object_2.Display_d();

getch();

return 0;

}

Output

Im Constructor

Values :10 20

Values :10 20

 

Leave a Reply

Your email address will not be published. Required fields are marked *