Reputation: 739
Is there a fast way to to make an exact replica of an exisitng object in C++?
For example I have a default constructor that left most variables uninitialized and those variables are to be set later in the process. Then I want to make a exact copy of that object with all the data already initialized.
I heard there is a copy constructor in c++ but I'm not sure how to use it nor do I know if it fits my situation. Is there a convenient way of doing this other than copying all data manually?
EDIT: I have lots of user-defined type in this object (graphs, etc complicated stuff)
Upvotes: 2
Views: 4703
Reputation: 3345
You have to define the copy process manually. How else would the compiler know, if you are re-using the same resource or want a copy of that resource?
The default copy constructor (which is always there, unless you define your own one), will copy all data by simple assignment, which can be harmful with pointers, files, connection and all other external resources.
Upvotes: 0
Reputation: 19052
If your members are POD types, or themselves are copyable, then the compiler will generate a default copy constructor.
class Foo
{
public:
Foo(int x, int y, int z, const std::string& name)
: x_(x), y_(y), z_(z), name_(name)
{
}
private:
int x_, y_, z_;
std::string name_;
};
This example class is copyable using the default copy constructor. The following are all correct:
Foo a(1, 2, 3, "four");
// copy construct b from a, using the compiler provided default copy constructor
Foo b(a);
Foo c(5, 6, 7, "eight");
// copy c from b, c's current values are "lost"
c = b;
If you have a class that contains user defined types that do not perform as expected with a shallow copy, then you will need to write your own copy constructor, assignment operator and destructor. This is why most experienced C++ developers will stay away from raw pointers (and other similar concepts) whenever possible.
class BadFoo
{
public:
BadFoo() : x_(new int(5))
{
}
// ... You need to manage the memory of x_ on your own
// This means following the rule of 3 (C++03) or 5 (C++11)
private:
int* x_;
};
See: Rule of Three
Upvotes: 1
Reputation: 1637
Copy constructor is the way to go.
class MyObject
{
public:
MyObject(const MyObject& other);
private:
int x;
float y;
std::string s;
}
MyObject::MyObject(const MyObject& other)
: x(other.x), y(other.y), s(other.s)
{}
Upvotes: 0
Reputation: 5064
You need to use a copy constructor. If you do not implement, the compiler will come up with a default one for you. If there are members that cannot be copied by value (like pointers that get dynamically allocated), it is better to implement it yourself, and make sure a deep copy is created.
However, don't forget that once you choose to implement copy-constructor, it is a sign that you most probably need to implement the copy-assignment operator, and the destructor as well. This is generally referred as the Rule of the three in C++.
Upvotes: 1