• Home
  • Copy Constructor in C++

Copy Constructor in C++

A copy constructor is a special type of constructor in C++ that is used to create a new object as a copy of an existing object. It is a member function that initializes an object using another object of the same class. The syntax for defining a copy constructor is:

class_name (const class_name &other_object);

Here, other_object is the object that is being copied. The copy constructor is called automatically when an object is passed by value, returned by a function, or initialized using the assignment operator.

For example, consider the following class definition:

class Example {
private:
int value;
public:
Example(int v) {
value = v;
}
Example(const Example &other) {
value = other.value;
}
int getValue() {
return value;
}
};

In this example, the class Example has a single private member variable value and a public constructor that takes an integer value as an argument. The copy constructor is defined as a public member function that takes a reference to an Example object as an argument. It initializes the value of the new object with the value of the other object.

To use the copy constructor, you can create an object and initialize it with the value of another object using the assignment operator:

Example obj1(10);
Example obj2 = obj1;

In this case, the copy constructor is called automatically to create a new object obj2 that is a copy of obj1. The value of obj2 will be 10, which is the value of obj1.

You can also pass an object to a function by value or return it from a function, and the copy constructor will be called automatically to create a copy of the object:

void test(Example obj) {
// obj is a copy of the object passed as an argument
// ...
}

Example test() {
Example obj(10);
return obj;
}

In both of these cases, the copy constructor is called to create a new object that is a copy of the original object.