So i came up with these two different methods in class A, copy1 and copy2.
class A{ public: A(int na, int nb, int nc){ a = na; b = nb; c = nc; } A(){ a = -1; b = -2; c = -3; } A * copy1(){// specified deep copy A * clone = new A; //takes what i need and puts it in the copy clone->a = a; clone->b = b; clone->c = c; return clone; } A * copy2(){ // Stack-copy-like copy A * clone = new A; *clone = *this; //Makes the compiler do it return clone; } void print_data(){ std::cout << a << " " << b << " " << c << "\n"; } private: //the variables int a; int b; int c; int d; int e; };//Testingint main(){// setup object A test = A(-5,-3,5); // Create copies A * test2 = test.copy1(); A * test3 = test.copy2(); //overwrite initial object test = A(); //Write out data test.print_data(); test2->print_data(); test3->print_data();}
This outputs:
-1 -2 -3
-5 -3 5
-5 -3 5
Which proves that the copying went as expected. As I see it copy2 is easiest to implement as I don't need to specify which variables to copy, but is copy1 faster? Are there any other pros or cons? Are there better ways to copy objects?