How to clone objects in C++
This post will discuss how to clone objects in C++.
1. Using copy constructor
A copy constructor is a special constructor to initialize a new object with the copy of an existing class object. It specifies the actions to be performed by the compiler while copying objects. The following C++ program demonstrates the usage of a copy constructor. It initializes an object with the copy of all the fields from another object of the same type.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> class Point { public: int x, y; // constructor Point(); Point(int x, int y): x(x), y(y) {} // copy constructor Point(const Point &rhs) { this->x = rhs.x; this->y = rhs.y; } }; int main() { Point p {0, 1}; std::cout << "Original object (" << p.x << ", " << p.y << ")\n"; Point copy(p); std::cout << "Copied object (" << copy.x << ", " << copy.y << ")\n"; return 0; } |
Output:
Original object (0, 1)
Copied object (0, 1)
2. Using assignment operator
Another simple and efficient solution is using the copy assignment operator to clone objects in C++. It can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> class Point { public: int x, y; // constructor Point(); Point(int x, int y): x(x), y(y) {} // copy assignment operator Point& operator=(const Point &rhs) { this->x = rhs.x; this->y = rhs.y; }; }; int main() { Point p {0, 1}; std::cout << "Original object (" << p.x << ", " << p.y << ")\n"; Point copy = p; std::cout << "Copied object (" << copy.x << ", " << copy.y << ")\n"; return 0; } |
Output:
Original object (0, 1)
Copied object (0, 1)
Note: The copy constructor and assignment operator should be used only when the object is not polymorphic. For polymorphic classes, provide an explicit clone() method instead.
That’s all about cloning objects in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)