c-plus-plus
  1. c-plus-plus-copy-constructor

C++ Object Class Copy Constructor

The copy constructor in C++ is a special type of constructor which is used to create a new object as an exact copy of an existing object of the same class.

Syntax

class ClassName {
  ClassName(const ClassName &source);
};

Example

#include <iostream>
using namespace std;

class Car {
public:
  string brand;
  string model;
  int year;
  Car(string b, string m, int y) {
    brand = b;
    model = m;
    year = y;
  }
  Car(const Car &source) {
    brand = source.brand;
    model = source.model;
    year = source.year;
  }
};

int main() {
  Car car1("Ford", "Mustang", 1999);
  Car car2 = car1; // using copy constructor
  cout << car2.brand << " " << car2.model << " " << car2.year << endl;
  return 0;
}

Output

Ford Mustang 1999

Explanation

In the example above, we have a Car class with a constructor that takes in brand, model, and year as parameters. We also have a copy constructor which takes in an object of the same class as its parameter.

In the main() function, we create a Car object car1 with the values "Ford", "Mustang", and 1999. We then create a new Car object car2 and initialize it with car1, which will use the copy constructor. Finally, we output the values of car2, which should be an exact copy of car1.

Use

The copy constructor is used when we need to create a new object that is an exact copy of an existing object. This can be useful in many situations, such as when we need to pass an object by value to a function or when we need to create a copy of an object for backup purposes.

Important Points

  • The copy constructor takes an object of the same class as its parameter.
  • The copy constructor is used to create a new object that is an exact copy of an existing object.
  • If a copy constructor is not defined in a class, the compiler will generate a default copy constructor which performs a shallow copy of all data members.
  • A shallow copy copies the values of the data members, but not the memory location of the pointers.

Summary

In this tutorial, we learned about the copy constructor in C++. We saw how it is used to create a new object as an exact copy of an existing object of the same class. We also saw an example of how to define and use a copy constructor in a class. Finally, we discussed the important points to keep in mind when using the copy constructor.

Published on: