A copy constructor is a special constructor in C++ that creates a new object by initializing it with an existing object of the same class. The purpose of the copy constructor is to create a new object that is a copy of the original object, with the same values for all of its data members.
The copy constructor is called in several situations:
When a new object is created from an existing object of the same class, using the copy constructor explicitly. When a new object is created from an existing object of the same class, implicitly, such as when an object is passed by value to a function. When an object is returned by value from a function. When an object is caught by value in a catch block.
Here’s an example of a copy constructor:
#include <iostream>
using namespace std;
class Person {
public:
Person(const char* name) {
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
Person(const Person& other) { // copy constructor
this->name = new char[strlen(other.name) + 1];
strcpy(this->name, other.name);
}
~Person() {
delete[] name;
}
void printName() {
cout << name << endl;
}
private:
char* name;
};
int main() {
Person p1("John");
Person p2 = p1; // copy constructor called implicitly
p1.printName();
p2.printName();
return 0;
}
In this example, we define a class called Person that represents a person with a name. The class has a single data member, name, which is a dynamically allocated C-style string. We define a constructor to initialize the name, a destructor to clean up the name when the object is destroyed, and a printName() function to print the name.
We also define a copy constructor that takes a reference to another Person object as its argument. The copy constructor creates a new object by allocating memory for its name member, and copying the contents of the name member from the original object.
In the main() function, we create two Person objects, p1 and p2. We then use the copy constructor implicitly to create a new object p2 that is a copy of p1. We call the printName() function on both objects to verify that the copy was successful. Note that since we defined a copy constructor, the compiler will not provide a default copy constructor for the class.