Lecture 4 - Copy Constructor Flashcards
Copy constructor
When a copy of an object is made, it is initialized using a special constructor
3 situations in which copy constructors are called
- assignment from one object to another at time of creation
- passing an object by value to a function
- returning an object by value from a function
Default copy constructor
simply copies values from one object to another //SHALLOW COPY
Shallow copy
copying values as they are from one object to another
Syntax of custom copy constructor
NewClass::NewClass (const NewClass & obj)
What is the issue with shallow copy?
If one of the data members is a reference type, the address is copied BUT the memory location is not
○ Both the original object and the copy point to the same memory location, which can lead to logical errors
Deep copy
Creating a new object and copying the values of all data members AND making new copies of all referred objects
The copied object shares nothing with the old object