Copy Constructor vs. Assignment Operator

Copy Constructor vs. Assignment Operator #

Copy constructor Assignment operator
It is called when a new object is created from an existing object, as a copy of the existing object This operator is called when an already initialized object is assigned a new value from another existing object.
It creates a separate memory block for the new object. It does not create a separate memory block or new memory space.
compiler implicitly provides a copy constructor, if no copy constructor is defined in the class. A bitwise copy gets created, if the Assignment operator is not overloaded.

Example

#include <iostream>
#include <stdio.h>
using namespace std;
 
class Test {
public:
    Test() {}
    Test(const Test& t)
    {
        cout << "Copy constructor called " << endl;
    }
 
    Test& operator=(const Test& t)
    {
        cout << "Assignment operator called " << endl;
        return *this;
    }
};
 
int main()
{
    Test t1, t2;
    t2 = t1;
    Test t3 = t1;
    getchar();
    return 0;
}

Output

Assignment operator called 
Copy constructor called 

Reference #