Copy Constructors in C++

title: Copy Constructors in C++ date: 2021-03-15 tags: #C++ #copyconstructor —

In C++, a copy constructor is a special member function that allows the creation of a new object as a copy of an existing object of the same class. It is invoked when a new object is created from an existing object, either explicitly or implicitly.

The syntax for a copy constructor is as follows:

ClassName(const ClassName& obj) {
    // code to perform deep copy
}

Here, ClassName is the name of the class for which the copy constructor is defined. The parameter const ClassName& obj is a reference to the object being copied.

In order to understand the need for copy constructors, let’s consider the following scenario:

class Person {
private:
    std::string name;
    int age;

public:
    Person(const std::string& n, int a) : name(n), age(a) {}

    // Copy constructor
    Person(const Person& obj) : name(obj.name), age(obj.age) {}

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    Person person1("John", 25);
    Person person2 = person1; // Copy constructor invoked

    person1.display(); // Output: Name: John, Age: 25
    person2.display(); // Output: Name: John, Age: 25

    return 0;
}

In the above example, person2 is created as a copy of person1 using the copy constructor. The copy constructor performs a deep copy of the member variables name and age from person1 to person2.

If a copy constructor is not explicitly defined, the compiler generates a default copy constructor, which does a shallow copy of the member variables. However, it is good practice to define a copy constructor explicitly when there are dynamically allocated resources (e.g., pointers) in the class, to ensure proper copying of data.

To summarize, a copy constructor is useful in situations where you need to create a new object that is an exact copy of an existing object. It allows you to control how the copying of data is performed, ensuring that the new object is fully independent of the original one.

I hope this article has provided you with a clear understanding of copy constructors in C++. Feel free to experiment with different scenarios and explore more advanced concepts related to C++ copy constructors.