A copy constructor is a type of constructor in C++ arena. It is a special constructor in C++ programming ethics. This will create an object as a copy of a previously created object. It is used to initialize the values to the functions. If you aren’t declared separately in a particular class, the class itself consider it as a copy constructor.
Here we provide 3 C++ program examples for a copy constructor methodology and its operations. Feel free to check it out learn more about a particular topic. If you want to know more about “Constructors & destructors” as well, feel free to visit our link to learn.
Copy Constructor Program 1:
#include<iostream.h>
#include<conio.h>
using namespace std;
// Class definition
class Arr1
{
int *J1;
int SAJ; // SIZE variable
public:
Arr1(int cy) // Constructor method
{
J1=new int[cy];
SAJ=cy;
}
~Arr1() // Destructor definition
{
delete[] J1;
}
// Copy constructor
Arr1(const Arr1 &a);
void set(int a, int k)
{
if(a>=0 && a<SAJ)
J1[a]=k;
}
int inp(int a)
{
return J1[a];
}
};
// Copy Constructor operation
Arr1::Arr1(const Arr1 &i)
{
int a;
J1=new int[i.SAJ];
for(a=0;a<i.SAJ;a++)
J1[a]=i.J1[a];
}
int main()
{
clrscr();
Arr1 NUM(8);
int j;
for(j=0;j<8;j++)
NUM.set(j, j);
for(j=7;j>=0;j--)
cout<<NUM.inp(j);
cout<<endl;
// It Creates Array & initialize with num
Arr1 Y(NUM); // Invoking to copy constructor
for(j=0;j<8;j++)
cout<<Y.inp(j);
getch();
return 0;
}
[SEE: C Program Tutorials] & [IT Companies Details]
C++ Program example 2:
Write a C++ program for using copy constructors in a class.
#include<iostream.h>
#include<conio.h>
// Class definition of Rectangle
class ClsRect
{
int W1, H1; // Width & Height parameters
public:
void InitValz(int, int); // Method declaration
int area(void)
{
return (W1*H1);
}
};
// Method definition
void ClsRect::InitValz(int x, int y)
{
W1=x;
H1=y;
}
// Main method
int main ()
{
ClsRect W,*X,*Y;
ClsRect *Z=new ClsRect[2];
X=new ClsRect;
Y=&W;
W.InitValz(1,2);
X->InitValz(3,4);
Z->InitValz(5,6);
Z[1].InitValz(7,8);
cout<<"W Area:"<<W.area()<<"\n";
cout<<"*X Area:"<<X->area()<<"\n";
cout<<"*Y Area:"<<Y->area()<<"\n";
cout<<"Z[0] Area:"<<Z[0].area()<<"\n";
cout<<"Z[1] Area:"<<Z[1].area()<<"\n";
getch();
return 0;
}
- Learn [ Aptitude ] – [ Placement Papers ] – [ Spoken English ]
Example code 3:
#include<iostream.h>
#include<conio.h>
// Class definition
class TimSlt
{
int D1a,M1o,Y1e;
public:
void Display();
TimSlt(int Da1,int Ma1,int Ye1); // Constructor with parameters
TimSlt(const TimSlt &); // This is called Copy constructor
};
void TimSlt::Display()
{
cout<<D1a<<" "<<M1o<<" "<<Y1e<<endl;
}
TimSlt::TimSlt(int Da1,int Ma1,int Ye1)
{
D1a=D11;
M1o=Ma1;
Y1e=Ye1;
}
TimSlt::TimSlt(const TimSlt &tmp)
{
cout<<"Data are copied"<<endl;
D1a=tmp.D1a;
M1o=tmp.M1o;
Y1e=tmp.Y1e;
}
int main()
{
clrscr();
TimSlt Tim1(03,12,1991);
Tim1.Display();
TimSlt Tim2(Tim1);
Tim2.Display();
getch();
return 0;
}