Copy Constructor in C++: Syntax, Types and Examples
Are you curious to know about copy constructors in C++ programming language? They are a great way to optimize and streamline the duplication of objects. But do you know how they work, what their types are, or why they are so important? In this blog post, we’ll cover all aspects of these powerful features. So, let’s begin understanding what copy constructors do and how to successfully implement them into your codebase.
Introduction to Constructors
Constructors in C++ are methods invoked automatically at the time of object creation to initialize the data members of the new objects. It has the same name as the class and is called a constructor because it constructs or provides the values for the object. A restriction that applies to a constructor is that it must not have a return type or void.
The following is the syntax for defining a constructor:
class CLASSNAME
{
………
public :
CLASSNAME([parameter_list]) // constructor definition
{
. . . . . .
}
. . . . . . . .
};
You should declare a constructor in the public section of the class, as it is invoked automatically when objects are created. Further, there are three types of constructors in C++: default, parameterized, and copy constructors.
In a default constructor, no argument is passed, and it is known as a constructor with no parameters. Parameterized constructors allow one or more arguments to pass. Copy constructors create an object based on the previously created object of the same class.
Constructors and similar C++ concepts are part of the core proficiencies required in data science, web development, and related domains. If you wish to pursue a career in these fields, check out trending job oriented courses with internship or job placement offers.
Copy Constructor Syntax in C++
Class_name(const class_name &object_name)
{
// body of the constructor.
}
The syntax of copy structure in C++ is “ClassName(const ClassName &objectToCopy)”, where “const” indicates no modification to the original object when copying will be made. For example, you have two strings, ‘stringA’ and ‘stringB’. If you wanted ‘stringB’ to take on all properties associated with ‘string A’, without modifying ‘stringA’, then using a copy constructor would do just that.
MyClass obj1; // Existing Object
MyClass obj2(obj1); // Creating new 'copy' of existing one
In this case, “obj2” is created as the new object, which will take on the same values as what was previously seen in “obj1”. To learn more about copy constructor and its syntax, consider opting for an in-depth C++ course.
Example of Copy Constructor in C++
#include <iostream>
using namespace std;
// Declare a class
class Rectangle {
private:
double width;
double length;
public:
// Initialize variables with a parameterized constructor
Rectangle(double w, double l) {
width = w;
length = l;
}
// Copy constructor with a Rectangle object as a parameter
// Copies data from the passed object
Rectangle(const Rectangle &obj) {
width = obj.width;
length = obj.length;
}
double calculatePerimeter() {
return 2 * (width + length);
}
};
int main() {
// Create an object of the Rectangle class
Rectangle rect1(4.0, 7.5);
// Copy contents of rect1 to rect2 using the copy constructor
Rectangle rect2(rect1);
// Print perimeters of rect1 and rect2
cout << "Perimeter of Rectangle 1: " << rect1.calculatePerimeter() << endl;
cout << "Perimeter of Rectangle 2: " << rect2.calculatePerimeter();
return 0;
}
Output
Perimeter of Rectangle 1: 23
Perimeter of Rectangle 2: 23
The copy constructor of the Rectangle class is used to create a duplicate object of an existing one by copying its contents. The code for this operation is as follows:
Rectangle(const Rectangle &obj) {
width = obj.width;
length = obj.length;
}
The constructor of this object takes a parameter that is a reference to another Rectangle class instance. This means the values stored in obj’s variables are then assigned to the new object, invoking the copy constructor and effectively copying all data from one object into another. In main(), two rectangle objects, rect1 and rect2 have been created and an example has been given where the contents of rect1 were copied over onto rect2 using this method.
// Copy contents of rect1 to rect2
Rectangle rect2(rect1);
In this instance, the rect2 object invokes its copy constructor by passing a reference to the rect1 object as an argument – namely &obj = &rect1. This is done for constructors to fulfill their purpose of initializing objects and executing default code when they are created.
Also Read: Array in C
Characteristics of Copy Constructor
The following are the key characteristics of a Copy Constructor:
- It is used to initialize a new object’s members by duplicating the members of an existing object. It accepts a reference to an object of the same class as a parameter.
- Copy initialization involves using the copy constructor, which carries out member-wise initialization; copying each individual member respectively between objects of identical classes.
- If not specified explicitly, this process will be handled automatically by compiler-generated code for creating such constructors within programs. These programs can be written in C++ language or similar languages that support Object Oriented Programming (OOP).
- The copy constructor is useful for creating copies of existing objects without having to redefine the object’s entire data structure and attributes again.
- It also allows a programmer to provide custom modifications while copying an object, such as altering members according to certain criteria or making other changes. These changes can be more difficult in regular ‘assignment’ type operations between two identical classes of objects
Types of Copy Constructors in C++
A copy constructor program in C++ program is categorized into the following two types.
1. Default Copy Constructor
A default copy constructor is an implicitly defined one that copies the bases and members of an object like how they would be initialized by a constructor. The order in which these elements are copied during this process follows the same logic of initialization used when creating new objects with constructors.
#include <iostream>
using namespace std;
class MyClass {
int number;
public:
void setNumber(int x) { number = x; }
void display() { cout << endl << "Number=" << number; }
};
int main()
{
MyClass instance1;
instance1.setNumber(20);
instance1.display();
// Implicit Copy Constructor Calling
MyClass instance2(instance1); // or instance2=instance1;
instance2.display();
return 0;
}
// Output:
// Number=20
// Number=20
2. User-Defined Copy Constructor
A user-defined copy constructor is necessary when an object holds pointers or references that cannot be shared, such as a file. In these cases, it’s recommended to also create a destructor and assignment operator in addition to the copy constructor.
#include <iostream>
using namespace std;
class MyClass {
int number;
public:
void setNumber(int x) { number = x; }
MyClass() {} // default constructor with empty body
MyClass(MyClass &other) { // copy constructor
number = other.number;
}
void display() {
cout << endl << "Number=" << number;
}
};
int main() {
MyClass instance1;
instance1.setNumber(20);
instance1.display();
MyClass instance2(instance1); // or instance2=instance1; copy constructor called
instance2.display();
return 0;
}
// Output:
// Number=20
// Number=20
A user-defined copy constructor may be necessary when an object contains pointers or any kind of runtime resource allocation, such as file handles or network connections. With a custom copy constructor, it is possible to achieve deep copies instead of the shallow ones created by default constructors. The user can ensure that the pointers in copied objects are directed toward new memory locations with this method.
When is the Copy Constructor in C++ Used?
A copy constructor is called when an object of the same class is:
- Returned by value
- Passed as a parameter to a function
- Created based on another object of the same class
- When a temporary object has been generated by the compiler
Though a copy constructor may be called in some instances, there is no guarantee that it will always be used. The C++ standard allows for the compiler to eliminate redundant copies under specific conditions such as return value optimization (commonly referred to as RVO).
Difference Between Copy Constructor and Assignment Operator
Copy Constructor | Assignment Operator |
---|---|
It is an overloaded constructor. | It is an operator. |
Initializes a new object with an already existing one. | Assigns the value of one object to another already existing one. |
Has different memory locations for each object. | The same memory location is used, but different variables may point to it. |
A default copy constructor is provided if not defined. | Bitwise copy is provided when the operator is not overloaded. |
It creates a new object using an existing element. | Assigns an existing object to a new one. |
Differences Between Initialization and Assignment in C++
In the following code segment:
MYClass a;
MYClass b=a;
The variable “b” is initialized to “a” since it is created as an exact copy of another variable. This implies that when we create “b”, its value will go from containing unwanted data directly to holding the same value immediately without any intermediate step.
On the other hand, in this revised code example:
MYClass a, b;
b = a;
The statement “MYClass a, b;” initializes two variables – ‘a’ and ‘b’. The second line of code “b = a” assigns the value contained in variable ‘a’ to another (variable) object ‘b’. This demonstrates the difference between assignment and initialization. Assigning new values or instructions to an existing variable is known as an assignment. On the other hand, when objects receive values at their time of creation, it is referred to as initialization.
Conclusion
Copy constructors in C++ are an essential tool for effective software programming. Not only do they allow for objects to be efficiently duplicated within code, but they also provide better resource and memory management when dealing with pointers or other runtime resources. Programmers must understand the differences between initialization and assignment and master using these copy constructors to create great applications.
Are you a programmer looking for jobs in this domain? Check out this guide on C++ interview questions with proper coding examples to help you crack your next interview with ease.
FAQs
In C++, the default constructor has an empty body and does not assign default values to data members. The copy constructor is not empty and copies all data members of the passed object to the newly created object.
When the copy constructor is declared private, you cannot copy the class’s objects. It is useful when the class has pointer variables or dynamically allocated resources.
Yes, we can make the copy constructor private. In this case, the constructor can only be called from within the class itself. These constructors are made private when the class is not intended to be used as a standalone object but as a base class for inheritance.
Arguments to a copy constructor must be passed as a reference to avoid unnecessary copying of objects. If an argument is passed by value, the copy constructor is called indefinitely to make a copy of the argument. This results in an infinite loop.
The argument in a copy constructor should be const because const reference enables you to read the value but not modify it within the function. This ensures that the objects are not accidentally modified. Const argument is essential while working with temporary objects.
Copy constructors are required in C++ to initialize the data members of a newly created object in a class by copying the data members of an existing object of the same class.