when copy constructor and overloaded assignment operator is called? The difference between the copy constructor and the assignment operator is confusing concept for a new programmer. To keep the concept with the mind remember the purpose. Let us discuss the purpose of copy constructor and assignment operator.

  • copy constructor is used to create an object from existing object ( already created ).
  • assignment operator can not create new object. it works only on already created objects. it means when we assign one already created object to an already existing object.

Let us see below example and its output.

#include <iostream>
using namespace std;

class foo {
	int a;
public:
	foo() :
		a(5) {
		cout << "***********************************\n";
		cout << "default constructor called \n";
		cout << "***********************************\n";
	}
	foo(const foo &foo_obj) {
		this-> a = foo_obj.a;
		cout << "***********************************\n";
		cout << "copy constructor called \n";
		cout << "***********************************\n";
	}
	foo& operator =(const foo &foo_obj) {
		cout << "***********************************\n";
		cout << "assignment operator called \n";
		cout << "***********************************\n";
	}
};
int main() {
	foo obj_1;
	foo obj_2;
	obj_1 = obj_2; // assignment operator called
	foo obj_3 = obj_1;// copy constructor called
	return 0;
}

Output

***********************************
default constructor called 
***********************************
***********************************
default constructor called 
***********************************
***********************************
assignment operator called 
***********************************
***********************************
copy constructor called 
***********************************
  • When passing an object by value, copy constructor is getting called.
  • When an object is returned from a function by value, copy constructor is getting called.
#include <iostream>
using namespace std;

class foo {
public:
	int a;
	foo() :
		a(5) {
		cout << "default constructor called \n";
	}
	foo(const foo &foo_obj) {
		this-> a = foo_obj.a;
		cout << "copy constructor called \n";
	}
	foo& operator =(const foo &foo_obj) {
		cout << "Assignment called \n";
	}
};
void print(foo obj)
{
	cout << obj.a << endl;
}
foo changeData(foo obj)
{
	obj.a = 6;
	return obj; // copy constructor called
}
int main() {
	foo obj; // called default constructor
	print(obj); // called copy constructor
	obj = changeData(obj); // copy constructor called and assignment called
	return 0;
}

Ref:

http://www.csee.umbc.edu/~cress1/ia/Deliverables/appendix/202-CopyAssignment.PDF



Related Contents to follow