Copy constructor vs assignment operator in C++

Difficulty Level: Rookie

Consider the following C++ program.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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; 
chevron_right

Output:
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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

References:
http://en.wikipedia.org/wiki/Copy_constructor

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

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.




Article Tags :
C++
Practice Tags :