why is it in function test2 the copy constructor is called twice ?
Begin the ouput :Code:#include <cstdlib>
#include <iostream>
using namespace std;
class strings
{
char str[256];
public :
strings(const char *s)
{
strcpy(str, s);
}
strings(const strings &s)
{
cout << "copy constructor = " << s.str << endl;
strcpy(str, s.str);
}
~strings(void)
{
cout << "Destructing string " << str << endl;
}
void test1(const strings Obj1)
{
cout << "in test1 " << Obj1.str << endl;
}
strings test2(const strings Obj2)
{
cout << "in test2 " << Obj2.str << endl;
return(Obj2);
}
};
int main(int argc, char *argv[])
{
strings s1("Hellow world");
cout << "Calling test1 : " << endl;
s1.test1(s1);
cout << "\n\nCalling test2" << endl;
s1.test2(s1);
system("PAUSE");
return EXIT_SUCCESS;
}
Calling test1 :
copy constructor = Hellow world
in test1 Hellow world
Destructing string Hellow world
Calling test2
copy constructor = Hellow world
in test2 Hellow world
copy constructor = Hellow world
Destructing string Hellow world
Destructing string Hellow world
Press any key to continue . . .
End output.
The part in blue I understand. this is from assinging s1 to obj2.
But where does the part in orange comes from ?