copy constructor

Copy constructor is type of constructor which  helps to create a new object using the copy of an old object of the same class. So in simple term copy constructor is used to initialize on object from another object of the same class. A copy constructor of class A takes

(1) First parameter is A&, const A&, volatile A&, or const volatile A&
(2) Either there are no other parameters, or the rest of the parameters all have default values.

Syntax  and Declaration of copy constructor

class name ( const class name & )

Note: Copy constructor takes reference of same class.

Let us take an example:

#include<iostream>
using namespace std;

class A {
	int a;
public:
	A() {
		a = 5;
	}
	void print() {
		cout << a;
		cout << endl;
	}
};

int main() {
	A a;
	a.print();

	// object b is initializing from old object a of class A
	A b(a);
	b.print();

	return 0;
}

 

Here at above code when we have created object b and initialize it with old object a through  below code

A b(a) ;

Here copy constructor is getting called. But we have not declared and defined any copy constructor in above example. Then how this happened? This is happened because

(1) When we do not write a copy constructor and assignment operator , c++ compiler  automatically creates one. so  for example if we make a class A like below.

class A {
	int a;
public:
	A() {
		a = 5;
	}
};

 

Then C++ compiler automatically convert your above code to

class A {
	int a;
public:
	A() {
		a = 5;
	}

	A(const A& xyz) {
		a = xyz.a;
	}
	A& operator=(const A& xyz) {
		a = xyz.a;
		return *this;
	}
};

 

copy constructor is called when:

(1) An object is returned by value
(2) An object is passed (to a function) by value as an argument
(3) An object is thrown
(4) An object is caught
(5) An object is placed in a brace-enclosed initializer list

 “Why we need to write own copy constructor if c++ compiler provides itself or in which case a programmer force to write or override copy constructor and assignment operator”

Answer: The default copy constructor only do shallow copy if we want deep copy then we have to provide our own copy constructor and assignment operator” for below link for details.

http://wikistack.com/deep-copy-and-shallow-copy-in-c/




Related Contents to follow