I was pointed to the following article:
http://www.codeproject.com/Tips/78946/C-Copy-Constructor-in-depth
and we have the code:
class string
{
// constructor
string(char* aStr)
{
str = new char[sizeof(aStr)];
strcpy (str,aStr);
}
// destructor
~string()
{
del str;
}
char *getChars(){ return str; }
char* str;
};
void function (string str)
{
// do something
}
void main ()
{
string str("hello");
function(str);
function(str); // program crashes
}
I do not understand why in main
, there would be a problem with the second call to function
? Surely when str
is passed in to the first call, this would only be a copy of str
and therefore anything done to str
within function
would not affect the variable str
declared in main
?