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)
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