I am looking at the code and explanations from this page and I don't quite get it. https://www.geeksforgeeks.org/copy-constructor-in-cpp/
Below is the example I am confused on. why does str2.change("GeeksforGeeks");
cause str1 to also change? I ask because change
does the exact same thing as the copy constructor. They both assign a new char array to s.
#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; } // Function to print string
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;
}