fork download
  1. #include <iostream>
  2.  
  3. class MyClass {
  4. public:
  5. int* data;
  6.  
  7. // Constructor
  8. MyClass(int value) {
  9. data = new int(value); // Dynamically allocate memory
  10. }
  11.  
  12. //copy constructor, deep copy
  13. MyClass(const MyClass& other){
  14. data = new int(*other.data);
  15. }
  16.  
  17. MyClass& operator=(const MyClass& other){
  18. if(this != &other){
  19. delete data;
  20. data = new int(*other.data);
  21. }
  22.  
  23. return *this;
  24. }
  25.  
  26. // Destructor
  27. ~MyClass() {
  28. delete data; // Free the allocated memory
  29. }
  30. };
  31.  
  32. int main() {
  33. MyClass obj1(42);
  34. MyClass obj2 = obj1;
  35. MyClass obj3(66);
  36. obj3 = obj2;
  37.  
  38. std::cout << "obj1 data: " << *obj1.data << std::endl;
  39. std::cout << "obj2 data: " << *obj2.data << std::endl;
  40. std::cout << "obj3 data: " << *obj3.data << std::endl;
  41.  
  42. *obj2.data = 100; // Modify obj2's data
  43.  
  44. std::cout << "After modification:" << std::endl;
  45. std::cout << "obj1 data: " << *obj1.data << std::endl;
  46. std::cout << "obj2 data: " << *obj2.data << std::endl;
  47. std::cout << "obj3 data: " << *obj3.data << std::endl;
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
obj1 data: 42
obj2 data: 42
obj3 data: 42
After modification:
obj1 data: 42
obj2 data: 100
obj3 data: 42