A Copy Constructor in C++ is a special type of constructor used to initialize a new object as a copy of an existing object. It is an overloaded constructor that takes a reference to an object of the same class as its parameter.
• provided by the compiler if the programmer does not define one.
• It performs a shallow copy, which is a simple member-wise copy of the object's attributes.
• Explicitly defined by the programmer to perform deep copies or to manage resources like dynamic memory, file handles, etc.
• Typically used when shallow copying is insufficient.
ClassName(const ClassName &old_object);
<#include <iostream>>
class Rectangle {
public:
int width;
int height;
// Default Constructor
Rectangle() : width(0), height(0) {}
// Parameterized Constructor
Rectangle(int w, int h) : width(w), height(h) {}
// User-Defined Copy Constructor
Rectangle(const Rectangle &rect) {
width = rect.width;
height = rect.height;
}
// Method to display dimensions
void display() const {
std::cout << "Width: " << width << ", Height:
" << height << std::endl;
}
};
int main() {
Rectangle rect1(10, 20); // Create a Rectangle object using the parameterized
constructor
Rectangle rect2 = rect1; // Create a copy of rect1 using the copy constructor
std::cout << "Dimensions of rect1:" << std::endl;
rect1.display();
std::cout << "Dimensions of rect2 (copy of rect1):" << std::endl;
rect2.display();
return 0;
}
Dimensions of rect1:
Width: 10, Height: 20
Dimensions of rect2 (copy of rect1):
Width: 10, Height: 20
• Performed by the default copy constructor.
• Copies all member variables of the object as they are.
• If the object contains pointers, both the original and the copied object will point to the same memory location, which can lead to issues like double deletion.
• Requires a user-defined copy constructor.
• Allocates separate memory for pointers and copies the actual values, ensuring that the original and the copy do not share the same memory locations.
• Prevents issues like double deletion and dangling pointers.