0

I am having doubt in the below code,that in the absence of a copy constructor default copy constructor invokes and does a shallow copy,after which str1.s and str2.s both are pointing to string "GeekQuiz".

But after i delete str2.s its destruct-or gets called and sets it to NULL,but str1.s is still pointing to freed memory.

Now when i allocate a new string "GeeksforGeeks"and point str2.s to it , i dont understand why str1.s is also pointing to same new string "GeekforGeek"

 #include < iostream >
 #include < cstring >
 using namespace std;

 class String
 {
     private:
     char *s;
     int size;
  public:
     String(const char *str = NULL); // constructor
     ~String() { delete [] s;  }// destructor
     void print() { cout << s << endl; }
     void change(const char *);  // Function to change
 };

 String::String(const char *str)
 {
     size = strlen(str);
     s = new char[size+1];
     strcpy(s, str);
 }

 void String::change(const char *str)
 {
    delete [] s;
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
 }

 int main()
 {
      String str1("GeeksQuiz");
      String str2 = str1;

      str1.print(); // what is printed ?
      str2.print();

      str2.change("GeeksforGeeks");

      str1.print(); // what is printed now ?
      str2.print();
      return 0;
    }
haris
  • 2,003
  • 4
  • 25
  • 24
  • 2
    Fyi, debuggers are *made* for this very type of questionable inspection. – WhozCraig May 08 '16 at 10:00
  • 1
    Behavior you showed happens just because heap manager finds first free space at same memory location as old `s` which you deleted, it's not guaranteed it's just pure luck. – PcAF May 08 '16 at 10:15

0 Answers0