fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class StringEdit {
  5. char* p; // pointer to hold characters
  6. int len; // length of string
  7.  
  8. public:
  9. // Default constructor
  10. StringEdit() {
  11. len = 0;
  12. p = nullptr;
  13. }
  14. // Parameterized constructor
  15. StringEdit(const char* arr, int l) {
  16. len = l;
  17. p = new char[len];
  18. for (int i = 0; i < len; i++) {
  19. p[i] = arr[i];
  20. }
  21. }
  22.  
  23. //copy constructor
  24. // StringEdit(const StringEdit& newStr) {
  25.  
  26. // len = newStr.len;
  27. // p = new char[len];
  28. // for (int i = 0; i < len; i++) {
  29. // p[i] = newStr.p[i];
  30. // }
  31.  
  32. // }
  33.  
  34. // Copy assignment operator overload
  35. StringEdit& operator=(const StringEdit& newStr) {
  36. if (this != &newStr) { // avoid self-assignment
  37. delete[] p; // free old memory
  38.  
  39. len = newStr.len;
  40. p = new char[len];
  41. for (int i = 0; i < len; i++) {
  42. p[i] = newStr.p[i];
  43. }
  44. }
  45. return *this;
  46. }
  47.  
  48. // Display function
  49. void display() {
  50. for (int i = 0; i < len; i++) {
  51. cout << p[i];
  52. }
  53. cout << endl;
  54. }
  55.  
  56. // Destructor
  57. ~StringEdit() {
  58. delete[] p;
  59. }
  60. };
  61.  
  62. int main() {
  63. StringEdit s; // empty string
  64. StringEdit dummy("abcde", 5); // parameterized constructor
  65. s = dummy; // uses overloaded operator=
  66.  
  67. cout << "Dummy string: ";
  68. dummy.display();
  69. cout << "Copied string (s): ";
  70. s.display();
  71. //cout << "Copied string (s): ";
  72. return 0;
  73. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Dummy string: abcde
Copied string (s): abcde