Copy constructors are special member functions in C++ that are automatically called when an object is copied. They are used to create a new object that is a copy of an existing object.
Syntax
class MyClass {
public:
MyClass(const MyClass& other); // Copy constructor declaration
};
When Copy Constructors Are Called
Object initialization: When an object is initialized using another object of the same class.
Function arguments: When an object is passed as an argument to a function.
Return values: When an object is returned from a function.
Example
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person(string name, int age) {
this->name = name;
this->age = age;
}
Person(const Person& other) {
name = other.name;
age = other.age;
cout << "Copy constructor called" << endl;
}
};
int main() {
Person p1("Alice", 25);
Person p2 = p1; // Copy constructor is called
cout << "p2.name: " << p2.name << endl;
cout << "p2.age: " << p2.age << endl;
return 0;
}
Output:
Copy constructor called
p2.name: Alice
p2.age: 25
Shallow Copy vs. Deep Copy
Shallow Copy: A shallow copy creates a new object and copies the addresses of the data members from the original object. This means that both objects share the same data.
Deep Copy: A deep copy creates a new object and copies the values of the data members from the original object. This means that the two objects have independent copies of the data.
Example: Deep Copy
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
string address;
Person(string name, string address) {
this->name = name;
this->address = address;
}
Person(const Person& other) {
name = other.name;
address = other.address; // Deep copy of address
}
};
int main() {
Person p1("Alice", "123 Main St");
Person p2 = p1;
p1.address = "456 Elm St";
cout << "p1.address: " << p1.address << endl;
cout << "p2.address: " << p2.address << endl;
return 0;
}
Output:
p1.address: 456 Elm St
p2.address: 123 Main St
In this example, a deep copy is performed for the address data member, ensuring that the two objects have independent copies.
Key Points:
Copy constructors are automatically called when objects are copied.
Shallow copies can lead to unexpected behavior when data members are pointers or references.
Deep copies ensure that objects have independent copies of their data.
By understanding copy constructors and the difference between shallow and deep copies, you can effectively manage object creation and prevent unintended side effects in your C++ programs.
Comments