Skip to content
Related Articles

Related Articles

Copy constructor vs assignment operator in C++
  • Difficulty Level : Medium
  • Last Updated : 08 Jul, 2019

Difficulty Level: Rookie

Consider the following C++ program.

using namespace std; 
class Test 
    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; 
    return 0; 

Assignment operator called
Copy constructor called

Copy constructor is called when a new object is created from an existing object, as a copy of the existing object (see this G-Fact). And assignment operator is called when an already initialized object is assigned a new value from another existing object.

t2 = t1;  // calls assignment operator, same as "t2.operator=(t1);"
Test t3 = t1;  // calls copy constructor, same as "Test t3(t1);"


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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :