Object Copying by Assignment or By Copy Constructor
Understanding object copying by assignment or by using copy constructor call.
Learning Objectives
- Understanding object copying vis-a-vis copy constructor based copying.
Source Code
|
Run Output
Code Understanding
class C { //Class template C declared
public:
int x; // Integer value x declared as public so that it can be printed in main
C(){ x=10;} //Default constructor initialising value of x as 10
C(C& D) { x=30;} //Copy constructor initialising value of x as 30
};
int main() {
C c1,c2; //Declaring two objects c1 and c2, default constructor will be called for both
cout<<c1.x<<” “<<c2.x<<endl;
Both should print 10 as default constructor is called in both cases.
c2=c1;
Here object copying is being done so all data members will be copied to a new memory location.
c1.x=20;
x from first object being reassigned to 20.
cout<<c1.x<<” “<<c2.x<<endl;
20 and 10 gets printed as object location of c2 is different and is not reassigned.
C c3(c1);
This is object copying using copy constructor routine.
cout<<c1.x<<” “<<c3.x<<endl;
Here c1.x was 20 as previously reassigned and c3.x would be 30 as copy constructor is being called now.
return 0; }
Notes
- Object copying by direct assignment copies all the data members and references, but references may not be fully compatible. String references, file pointer references etc. may fail with object copying but copy constructor allows to set things right by giving full control over all the data members of the class.
- The proof of difference between object copying and copy constructor based copying is little complex to understand, however, geeks may be interested in seeing this proof.
http://www.cs.rpi.edu/courses/spring01/cs2/wksht10/wksht10.html
Suggested Filename(s): objcopy.cpp,objasgn.cpp
CSKC| Created: 26-Apr-2019 | Updated: 26-Apr-2019|