When I read about copy constructor and copy assignment constructor, what I understood is that both gives away their properties one to another, and that both of them are declared implicitly by compiler (if not defined). So both must be exist whether doing something useful or not.
Then I tested this code:
#include <iostream>
using namespace std;
class Test {
public:
Test () {
cout << "Default constructor" << endl;
}
Test (const Test& empty) {
cout << "Copy constructor" << endl;
}
Test& operator=(const Test& empty) {
cout << "Copy assignment operator" << endl;
}
private:
};
int main () {
Test a; // Test default constructor
Test b (a); // Test copy constructor
Test c = b; // Test copy assignment constructor
system ("pause");
return 0;
}
But it seems the copy assignment operator is not called at all. I tried with three conditions:
Everything included. It prints out:
// Default constructor
// Copy constructor
// Copy constructor # Why not prints out "Copy assignment operator"?
Whitout copy assignment operator just copy constructor. It prints out:
// Default constructor
// Copy constructor
// Copy constructor # Why it's printed out even though I didn't define it?
Whitout copy constructor just copy assignment operator. It prints out:
// Default constructor # Why "Copy assignment operator" is not printed out?
Only constructor. It prints out:
// Default constructor # Understandable
So, it's like the compiler doesn't even care if I define the copy assignment operator or not. None of the four examples above prints out "Copy assignment operator". So when did it get called, if it is really exists and has a meaning?
Test c = b
is an initialization, not an assignment.
If you had done this:
Test c;
c = b;
Then it would have called the copy assignment operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With