📌 What is a Copy Constructor in C++?
A copy constructor is a special member function that initializes a new object using an existing object of the same class. Its signature takes a constant reference to an object of its own class: ClassName(const ClassName& other). It is automatically invoked during three primary scenarios: (1) when an object is initialized from another of the same type (e.g., Obj a = b;), (2) when an object is passed by value into a function parameter, and (3) when an object is returned by value from a function. Understanding how it handles heap memory allocation distinguishes robust C++ software engineering from memory-corrupting code.
#include
#include
class UserProfile {
private:
std::string username;
int loginCount;
public:
// Parameterized Constructor
UserProfile(std::string uname, int count) : username(uname), loginCount(count) {
std::cout << "Parameterized Constructor invoked for: " << username << "\n";
}
// Explicit Copy Constructor
UserProfile(const UserProfile& other) {
username = other.username + "_copy"; // Custom modification on copy
loginCount = other.loginCount;
std::cout << "Copy Constructor invoked! Cloned from: " << other.username << "\n";
}
void display() const {
std::cout << "User: " << username << " | Logins: " << loginCount << "\n";
}
};
int main() {
UserProfile user1("Alice_Dev", 42);
// Invokes Copy Constructor
UserProfile user2 = user1;
user1.display();
user2.display();
return 0;
}
#include
#include
class ShallowContainer {
private:
char* data;
public:
ShallowContainer(const char* str) {
data = new char[strlen(str) + 1];
strcpy(data, str);
}
// Default compiler-generated copy constructor performs shallow copy (copies pointer address only!)
// ShallowContainer(const ShallowContainer& other) = default;
void display() const {
std::cout << "Data: " << data << " (Heap Address: " << (void*)data << ")\n";
}
~ShallowContainer() {
delete[] data; // Destructor frees heap memory
}
};
int main() {
ShallowContainer obj1("Enterprise Data");
{
ShallowContainer obj2 = obj1; // Shallow copy: obj2.data points to obj1.data!
obj2.display();
} // obj2 goes out of scope and deletes 'data'. obj1's pointer is now dangling!
// CRITICAL BUG: obj1 destructor runs here, attempting to delete already-freed memory!
// Result: Double free corruption / Segmentation Fault
return 0;
}
#include
#include
class DeepContainer {
private:
char* data;
size_t length;
public:
DeepContainer(const char* str) {
length = strlen(str);
data = new char[length + 1];
strcpy(data, str);
std::cout << "Allocated new heap memory at " << (void*)data << "\n";
}
// Custom Deep Copy Constructor
DeepContainer(const DeepContainer& other) {
length = other.length;
data = new char[length + 1]; // Allocate unique memory buffer
strcpy(data, other.data); // Copy actual string content, not just pointer
std::cout << "Deep copy performed! New heap memory allocated at " << (void*)data << "\n";
}
void display() const {
std::cout << "Data: " << data << " (Heap Address: " << (void*)data << ")\n";
}
~DeepContainer() {
delete[] data;
}
};
int main() {
DeepContainer obj1("Secure Enterprise Data");
DeepContainer obj2 = obj1; // Safely invokes deep copy constructor
obj1.display();
obj2.display();
return 0;
}
#include
#include
class ManagedBuffer {
private:
int* buffer;
size_t size;
public:
// 1. Constructor
ManagedBuffer(size_t s) : size(s), buffer(new int[s]()) {}
// 2. Destructor
~ManagedBuffer() { delete[] buffer; }
// 3. Copy Constructor (Deep Copy)
ManagedBuffer(const ManagedBuffer& other) : size(other.size), buffer(new int[other.size]) {
std::copy(other.buffer, other.buffer + size, buffer);
}
// 4. Copy Assignment Operator
ManagedBuffer& operator=(const ManagedBuffer& other) {
if (this == &other) return *this;
int* newBuffer = new int[other.size];
std::copy(other.buffer, other.buffer + other.size, newBuffer);
delete[] buffer;
buffer = newBuffer;
size = other.size;
return *this;
}
// 5. Move Constructor
ManagedBuffer(ManagedBuffer&& other) noexcept : buffer(other.buffer), size(other.size) {
other.buffer = nullptr;
other.size = 0;
}
// 6. Move Assignment Operator
ManagedBuffer& operator=(ManagedBuffer&& other) noexcept {
if (this == &other) return *this;
delete[] buffer;
buffer = other.buffer;
size = other.size;
other.buffer = nullptr;
other.size = 0;
return *this;
}
};
int main() {
ManagedBuffer b1(1000);
ManagedBuffer b2 = b1; // Copy Construction
ManagedBuffer b3(500);
b3 = b1; // Copy Assignment
return 0;
}
C++ COPY CONSTRUCTOR ARCHITECTURE MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Copy Strategy │ Underlying Mechanism │ Safety & Risk Profile │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ Default Shallow Copy │ Copies raw pointer addresses │ HIGH RISK: Multiple objects point to the same heap │
│ │ member-by-member. │ buffer, causing double-free crashes and memory leaks. │
│ Custom Deep Copy │ Allocates independent heap │ SAFE: Each object owns its unique memory buffer. │
│ │ buffers and duplicates data. │ Safely satisfies the Rule of Three/Five. │
│ Move Semantics (C++11) │ Transfers pointer ownership │ HIGH PERFORMANCE: Steals existing resources without │
│ │ without reallocating memory. │ deep copying (zero-overhead temporary transfer). │
├──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┤
│ ENGINEERING BEST PRACTICES: │
│ 1. Whenever a class manages raw pointers (`new`/`delete`), immediately implement or delete copy/move operations. │
│ 2. Prefer standard library containers (`std::vector`, `std::string`) which manage deep copying and RAII automatically.│
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘