Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the copy assignment operator called?

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:

  1. Everything included. It prints out:

    // Default constructor
    // Copy constructor
    // Copy constructor    # Why not prints out "Copy assignment operator"?
    
  2. 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?
    
  3. Whitout copy constructor just copy assignment operator. It prints out:

    // Default constructor # Why "Copy assignment operator" is not printed out?
    
  4. 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?

like image 594
Mas Bagol Avatar asked Mar 19 '15 20:03

Mas Bagol


1 Answers

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.

like image 95
emlai Avatar answered Oct 02 '22 06:10

emlai