The assignment operator and copy constructor often confuse people. Here is an example.

 
 
#include <iostream>
 
using namespace std;
 
 
class MyClass {
public:
 
    MyClass(int x = 34) {
        this->x = x;
    }
    MyClass & operator=(const MyClass & rhs) {
        cout << "calling assignment operator" << endl;
        this->x = rhs.x;
        return *this;
    }
 
private:
    int x ;
 
public:
    void printX() {
        cout << x << endl;
    }
 
};
 

If you create new object from old object like this.

 
int main () {
    MyClass * first = new MyClass(3);
 
    MyClass second = *first; // this is copy constructor. 
 
    first->printX();
    second.printX();
    return 0;
}
 

The assignment operator will not be called, instead the default copy constructor will be called.

This is most confusing scenario, because there is an assignment symbol there, we expect the assignment operator will be called and the parameter is right hand value. But it doesn't.

In below three cases, the copy constructor is called, instead the assignment operator:

  • 1.Declare a new object and initialize it with another object, like the example above.
  • 2.Passing the object by value.
  • 3. Return the object by value.

Next example will call the assignment operator.

 
int main () {
    MyClass * first = new MyClass(3);
 
    MyClass second;
        second = *first; // assignment operator
 
    first->printX();
    second.printX();
    return 0;
}