Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Copy Constructor vs Assignment Operator in C++

  • Difficulty Level : Medium
  • Last Updated : 01 Dec, 2021

Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
Copy constructor Assignment operator 
It is called when a new object is created from an existing object, as a copy of the existing objectThis 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.
It is an overloaded constructor.It is a bitwise operator. 
C++ 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. 

Syntax:

className(cont className &obj) {



// body 

}

Syntax: 

className obj1, obj2;

obj2 = obj1;

Consider the following C++ program. 

CPP




// CPP Program to demonstrate the use of copy constructor
// and assignment operator
#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;
    }
};
  
// Driver code
int main()
{
    Test t1, t2;
    t2 = t1;
    Test t3 = t1;
    getchar();
    return 0;
}
Output
Assignment operator called 
Copy constructor called 

Explanation: Here, t2 = t1;  calls the assignment operator, same as t2.operator=(t1); and  Test t3 = t1;  calls the copy constructor, same as Test t3(t1);

Must Read: When is a Copy Constructor Called in C++?

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!