Copy Constructor
A copy constructor in C++ is a special constructor that creates a new object as a copy of an existing object. It's used in several scenarios:
When an object is passed by value to a function.
When a function returns an object by value
When an object is initialized with another object of the same class
When the compiler generates a temporary object
Example:
Try it here.
In above example, here is what's happening:
We created simple implementation of
String
class.As data members, we have a
char* data
which will hold pointer to memory location of our char array"Hello"
.When we reassign our
String s2
tos1
, compiler will create a shallow copy ofs1
, which means, it will setconst* data
ofs2
to same memory location ifs1
's*data
pointer. I.e. both the objects will point to same memory location.As
String s1
andString s2
both were created using stack will be removed when our main function scope is done.First
s1
's destructor will be called, destructor will free memory of string"Hello"
, i.e. memory at pointer location*data
will be freed.Now when
s2
's destructor is called, which will try to free memory at location*data
, which has been already removed bys1
's destructor, as both*data
was pointing to same memory location.As the memory location pointed by
*data
is already free and no longer part of your application, it cannot be made free.Hence, your program will exit with compiler saying that this app tried to call free twice on a memory location Or kernel will shout that you tried to access something you do not own.
Key points about copy constructors:
Syntax: They take a const reference to an object of the same class as a parameter.
Default behaviour: If you don't define a copy constructor, the compiler provides a default one that performs a shallow copy (member-wise copy).
Deep vs. Shallow Copy: For classes with dynamically allocated resources, you often need to define a copy constructor to perform a deep copy, ensuring each object has its own independent copy of the resources.
Rule of Three/Five: If you define a copy constructor, you typically also need to define a destructor and a copy assignment operator (Rule of Three). In modern C++, you might also include a move constructor and move assignment operator (Rule of Five).
Prevention: You can prevent copying by declaring the copy constructor as
delete
:Performance: For large objects, passing by reference is often more efficient than passing by value to avoid unnecessary copying.
Copy constructors are crucial for proper resource management and preventing issues like double deletion or unintended shared state between objects, especially when dealing with dynamically allocated memory or other resources.
Last updated