The copy constructor is a constructor that initializes a object with the data values of another object is called copy constructor.
The copy constructor is used to:
Syntax/ The most common form of copy constructor is shown here −
Class-name (class-name &obj)
{
// body of copy constructor
}
A program that copy constructors is given as follows.
using namespace std;
class C {
private:
int i;
public:
C()
{
i=10;
cout<<" Default Constructor!! " <<endl;
}
C(C &s) //Copy constructor
{
i=s.i;
cout<<"The Value of i = " <<i;
}
};
int main(){
C x; //constructor call
C a(x); // copy constructor call
// C b=x; // copy constructor call
}
Default Constructor!!The Value of i =10
Example No.2 Copy Constructor
#include<iostream>using namespace std;class disk { private: int feet; float inch; public: disk(){ } disk(int f, float in) { feet=f; inch=in; } disk(disk &s) //Copy constructor { feet =s.feet; inch = s.inch; cout<<"Copy Constructor called!! " <<endl; } void show(){ cout<<"The Feet = " <<feet<<endlt; cout<<"The inch = " <<inch; } };int main(){ disk d1(5,7) ; //paramerized constructor call disk d2=d1; // copy constructor call d2.show(); }
Copy Constructor called!!The Feet= 5The inche= 7
0 Comments
Thanks for Supporting me