fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class MyClass
  5. {
  6. int * data;
  7. public:
  8. MyClass(int value)
  9. {
  10. data = new int(value);
  11. cout<<"consturctor called"<<endl;
  12. }
  13.  
  14. ~MyClass()
  15. {
  16. delete data;
  17. cout<<"destructor called"<<endl;
  18. }
  19.  
  20. MyClass(const MyClass &other)
  21. {
  22. data = new int(*other.data);
  23. cout<<"copy constructor called"<<endl;
  24. }
  25.  
  26. MyClass& operator=(const MyClass &other)
  27. {
  28. if(this != &other)
  29. {
  30. delete data;
  31. data = new int(*other.data);
  32. }
  33. return *this;
  34. }
  35.  
  36. int getValue() {
  37. return *data;
  38. }
  39. };
  40.  
  41.  
  42. int main() {
  43. MyClass obj1(10);
  44. MyClass obj2 = obj1; // Copy constructor
  45. MyClass obj3(20);
  46. obj3 = obj1; // Assignment operator
  47.  
  48. std::cout << "obj1 value: " << obj1.getValue() << std::endl;
  49. std::cout << "obj2 value: " << obj2.getValue() << std::endl;
  50. std::cout << "obj3 value: " << obj3.getValue() << std::endl;
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
consturctor called
copy constructor called
consturctor called
obj1 value: 10
obj2 value: 10
obj3 value: 10
destructor called
destructor called
destructor called