Deep Copy V/S Shallow Copy
#include <iostream>
#include <cstring>
class ShallowCopyExample {
public:
char* data;
// Constructor
ShallowCopyExample(const char* str) {
data = new char[strlen(str) + 1];
strcpy(data, str);
}
// Copy constructor (shallow copy)
ShallowCopyExample(const ShallowCopyExample& other) {
data = other.data; // Shallow copy of data
}
~ShallowCopyExample() {
delete[] data;
}
};
int main() {
ShallowCopyExample original("Hello, World!");
ShallowCopyExample shallowCopy = original; // Shallow copy
std::cout << "Original: " << original.data << std::endl;
std::cout << "Shallow Copy: " << shallowCopy.data << std::endl;
// Modify the data in the original object
original.data[0] = 'G';
std::cout << "Original: " << original.data << std::endl;
std::cout << "Shallow Copy: " << shallowCopy.data << std::endl; // Also modified
return 0;
}Last updated