Suppose it Tis a C ++ class, and if I execute T a = b;, is it a copy constructor or an assignment operator called?
My current experiment shows that the copy constructor is being called, but I don’t understand why.
#include <iostream>
using namespace std;
class T {
public:
T() : x("Default constructor") { }
T(const T&) : x("Copy constructor") { }
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
Thank!
source
share