The Wayback Machine - https://web.archive.org/web/20240910200507/https://www.geeksforgeeks.org/when-should-we-write-our-own-copy-constructor-in-cpp/
Open In App

When Should We Write Our Own Copy Constructor in C++?

Last Updated : 15 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference).

When should we write our own copy constructor?

C++ compiler provides a default copy constructor (and assignment operator) with class. When we don’t provide an implementation of the copy constructor (and assignment operator) and try to initialize an object with the already initialized object of the same class then the copy constructor gets called and copies members of the class one by one in the target object. 

But the problem with the default copy constructor (and assignment operator) is: 

  • When we have members that dynamically get initialized at run time, the default copy constructor copies this member with the address of dynamically allocated memory and not a real copy of this memory.
  • Now, both the objects point to the same memory, and changes in one reflect in another object.
  • Further, the main disastrous effect is, that when we delete one of these objects another object still points to the same memory, which will be a dangling pointer, and memory leak is also a possible problem with this approach.

So, we need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like a file handle, a network connection, etc.

Another use case of a copy constructor is when we want to copy only specific data members of the class from one object to another object and keep the remaining data members identical for each object, we can write our own copy constructor.

The default constructor does only shallow copy.

shallow-copy-concept-in-cpp

Deep copy is possible only with a user-defined copy constructor. In a user-defined copy constructor, we make sure that pointers (or references) of copied objects point to new memory locations.  

deep-copy-concept-in-cpp

Hence, in such cases, we should always write our own copy constructor (and assignment operator).

 


Previous Article
Next Article

Similar Reads

Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we initialize our own, the compiler by default creates a default constructor for every class; But, if we define our own constructor, the compiler doesn't create the default constructor. This is so because the default constructor does not take any argument and if two default constructors
1 min read
When should we write our own assignment operator in C++?
The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or a
3 min read
How to Write Our Own STL Container?
The Standard Template Library (STL) in C++ provides us with various data structures and algorithms. We have STL containers like vector, list, map, and set that we commonly use to store and manipulate data efficiently. However, there are situations where the existing STL containers may not meet our specific requirements, so we may want to create our
7 min read
How to implement our own Vector Class in C++?
The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can b
5 min read
Why copy constructor argument should be const in C++?
When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it. For example, pr
3 min read
Write your own memcpy() and memmove()
The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype. void * memcpy(void * destination, const void * source, size_t num);The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of t
4 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
When is a Copy Constructor Called in C++?
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value
2 min read
Copy Constructor in C++
A copy constructor is a type of constructor that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.   The process of initializing members of an object through a copy
7 min read
Copy Constructor vs Assignment Operator in C++
Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Copy constructor Assignment operator It is called when a new object is created from an existing object, as a copy of the existing objectThis operator is called when an already
2 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header <algorithm>. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Shallow Copy and Deep Copy in C++
In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. There are two ways that are used by C++ compiler to create a copy of objects. Copy ConstructorAssignment Operator// Copy Constructor Geeks Obj1(Obj); or Geeks Obj1 = Obj; // Default assignment operator Gee
6 min read
Implement Your Own sizeof
Here is an implementation. #include<stdio.h> #define my_sizeof(type) (char *)(&type+1)-(char*)(&type) int main() { double x; printf("%ld", my_sizeof(x)); getchar(); return 0; } Type is like a local variable to the macro. &type gives the address of the variable (double x) declared in the program and incrementing it with 1
2 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
Implementing own Hash Table with Open Addressing Linear Probing
Prerequisite - Hashing Introduction, Implementing our Own Hash Table with Separate Chaining in JavaIn Open Addressing, all elements are stored in the hash table itself. So at any point, size of table must be greater than or equal to total number of keys (Note that we can increase table size by copying old data if needed). Insert(k) - Keep probing u
13 min read
What is conversion constructor in C++?
Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++ A conversion constructor is a single-parameter constructor that is declared without the function specifier explicitly. The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor's class. Example:
3 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include <iostream> #include <vector> using namespace std; class MyClass { vector<int> vec; public: MyClass(vector<int> v) { vec = v; } void print()
2 min read
Constructor Delegation in C++
Sometimes it is useful for a constructor to be able to call another constructor of the same class. This feature, called Constructor Delegation, was introduced in C++ 11.An example program without delegation : C/C++ Code // A C++ program to demonstrate need of // constructor delegation. #include <iostream> using namespace std; class A { int x,
3 min read
Is body of a Default Constructor blank in C++?
The answer to this question depends upon 2 scenarios: Scenario 1: When there is a Virtual function in the program: In this scenario, compiler automatically creates virtual table(known as V-Table) and VVPTR(Virtual Void Pointer). V-Table contains the virtual method calls whereas VVPTR contain the address of virtual methods which are present in V-Tab
2 min read
How to create a List with Constructor in C++ STL
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about doubly linked list. For implementing a singly linked list, we use forward list. A list can be created with the he
2 min read
Dynamic Constructor in C++ with Examples
When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor. By using this, we can dynamically initialize the objects. Example 1: C/C++ Code #include <iostream> using namespace std; class geeks { const char* p; public: // default constructor geeks() { // allocating memo
3 min read
Difference Between Constructor and Destructor in C++
Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with argument
3 min read
Constructor in Multilevel Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multilevel Inheritance Derivation of a class from another derived class is called Multilevel Inheritance. Class A is the base class for the d
2 min read
Constructor in Multiple Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The construct
2 min read
How to Define the Constructor Outside the Class in C++?
A constructor is a special type of member function whose task is to initialize the objects of its class. It has no return type so can't use the return keyword and it is implicitly invoked when the object is created. Constructor is also used to solve the problem of initialization. It is called after the object is created.Same name as of class. Const
2 min read
C++ default constructor | Built-in types for int(), float, double()
A constructor without any arguments or with default values for every argument is treated as the default constructor. C++ allows even built-in types (primitive types) to have default constructors. The function style cast int() is analogous(similar in some way) to casting 0 to the required type.It will be called by the compiler when in need(precisely
2 min read
Is it possible to call constructor and destructor explicitly in C++?
A constructor is a special member function that is automatically called by the compiler when an object is created and the destructor is also a special member function that is also implicitly called by the compiler when the object goes out of scope. They are also called when a dynamically allocated object is allocated and destroyed, a new operator a
3 min read
Order of Constructor/ Destructor Call in C++
Prerequisite: Constructors Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that t
4 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Can a constructor be private in C++ ?
Prerequisite : Constructors A constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created. By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ? Answer : Ye
3 min read
Practice Tags :