Answer to Question #3657 in C++ for Suraj

Question #3657
What is copy constructor. Explain goal of copy constructor. Initializing pointer attribute of class for which the memory allocation takes place at run time.
Expert's answer
Copy constructor is a special method that program calls when creating a new object of a class as a copy of another existing object of the same type. This occurs when the new object is declared as a copy of another one, for example:
/* c++ code */
int i = 0;
int j (i);
/* end of code */
Here object "j" is a copy of another object "i".
Another example of using copy constructor is calling functions that takes as an argument an object, not reference to it:
/* c++ code */
void print(int & i) //here "i" is a reference and copying isn't performed
{ cout << i << endl; }
void print1(int i) //here "i" is a copy of parameter, so copy constructor is called
{ cout << i << endl; }
/* end of code */

Copy construct fills all fields of a new object so they become equal. But the problem is when there is a pointer attribute in the class.
Default copy constructor in such cases just copy pointer. So we need write own copy constructor to avoid this, because we must set
this pointer to new allocated memory and copy information from the value which is stored at address of the copied pointer attribute:
/* c++ code */
class MyClass
int * pint;
MyClass(): pint(new int (0)) {}
//this following below copy constructor allocates a new instance of memory for value of type "int"
//and assign to the value that is stored at this new address the value from the copied object
//Notice, that the pointer isn't copied
MyClass(MyClass& copy): pint(new int (*copy)) {} ~MyClass()
{ delete pint; }
/* end of code*/
Such copying when pointers are not copied but are created as a new instances of memory is called depth copying.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be the first!

Leave a comment

New on Blog