We’ve talked about Constructors in C++ already. One of the special methods, along with Destructors, that C++ offers. There is a third, special method which C++ offers. That is called a Copy Constructor.
The Copy Constructor is a special type of constructor, which is intended for use when you duplicate an object. Some people will call this process cloning.
While some properties are easy to process, others, are a bit more challenging. For example, copying a double from one class to another is easy. However, copying an array is a little bit more of a challenge. Anything with pointers are as well…and that’s because there are actually two types of copies, a shallow copy, and a deep copy.
Shallow Copy
A shallow copy looks at the data stored in an object. If it is a pointer, it copies the pointer address. This means that the two objects are pointing to the same memory address, and a change in one object’s property is a change in the other. This is most commonly seen with an object within an object.
As you can imagine, this might cause a lot of issues as properties change as the program progresses. So why would you even want to do that? Because it is very fast and takes less memory.
Imagine having to duplicate an array with 10,000 elements in it. Copying that data will take a long time going element by element. But to reference the same data, saves us a chunk of memory (80kb) and is a lot faster.
Deep Copy
A deep copy is slower, and will require more memory to be used. That’s because it looks at each property, and duplicates it. If it is a pointer, then it runs a copy constructor on that object, or creates a new pointer with a new data location, and uses that new copy.
This can take longer to run, but it is overall more accurate and less likely to have data being mangled. Great care does need to be made in order to work on processing all of this however, and ensuring that nothing is lost where some data is shallow copied and others is deep copied. This is the greatest threat to a deep copy.
The Copy Constructor
Creating the copy constructor is fairly simple. You overload a constructor, with a parameter of the type of the class.
Note: In some old compilers, you would have to compile your code at least once before you could write your copy constructor because without it, it didn’t know what the data object would look like and give an error…. weird. Right?
Circle::Circle(const Circle& template)
{
// copy data as needed
}
Note: Notice that we use the const
keyword to make sure we don’t accidentally change the original object!
Copy Constructors was originally found on Access 2 Learn