12

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?

Pharap
  • 3,826
  • 5
  • 37
  • 51
Mas Bagol
  • 4,377
  • 10
  • 44
  • 72

1 Answers1

19

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Does this mean that `Test c(b)` and `Test c = b` are identical? – Andreas Vennström Mar 19 '15 at 21:00
  • 6
    @AndreasVennström No, they're not identical. They both have the same effect in this code, but they are two different kinds of initialization. See http://bit.ly/1FLauIT and read about direct- and copy-initialization. – David G Mar 19 '15 at 21:52