Assume T
is a C++ class, and if I do T a = b;
, is the copy constructor or assignment operator called?
My current experiment shows the copy constructor is called, but do not understand why.
#include <iostream>
using namespace std;
class T {
public:
// Default constructor.
T() : x("Default constructor") { }
// Copy constructor.
T(const T&) : x("Copy constructor") { }
// Assignment operator.
T& operator=(const T&) { x = "Assignment operator"; }
string x;
};
int main() {
T a;
T b = a;
cout << "T b = a; " << b.x << "\n";
b = a;
cout << "b = a; " << b.x << "\n";
return 0;
}
$ g++ test.cc
$ ./a.out
T b = a; Copy constructor
b = a; Assignment operator
Thanks!
The copy constructor is called because
T a = b;
has the same effect as
T a(b);
It's an initialization, not an assignment. Long story short, it's just how the language works.
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