Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: "T a = b" -- copy constructor or assignment operator?

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!

like image 685
Ying Xiong Avatar asked Feb 11 '23 14:02

Ying Xiong


1 Answers

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.

like image 154
bstamour Avatar answered Feb 15 '23 12:02

bstamour