Here is my code:
#include <iostream>
#include <cstring>
using namespace std;
class someClass{
char * data;
public:
someClass(const char * s){
data = new char[strlen(s)+1];
strcpy(data,s);
cout << "constructing.."<<endl;
}
someClass(const someClass &o){
data = new char[strlen(o.data)];
strcpy(data,o.data);
cout << "copy construction" << endl;
}
~someClass(){delete [] data; cout << "destructing..." << endl;}
char * getValue(){return data;}
};
void showValue(someClass o){
char * s;
s = o.getValue();
cout << s << endl;
}
int main(int argc, char ** argv){
someClass str("Hello"), ptr("world");
showValue(str);
showValue(ptr);
}
and the output is:
constructing..
constructing..
copy construction
Hello
destructing...
copy construction
world
destructing...
destructing...
destructing...
Now first two 'constructing..' are triggered as soon as we create the object in main() on line 1.
showValue(str) runs and it triggers copy constructor for the word 'hello'. How? After creating and temporary object, it destructs itself when it's out of function.
showValue(ptr) runs and it triggers copy constructor for the word 'world'. How? After creating and temporary object, it destructs itself when it's out of function.
Lastly, in reverse order our str and ptr objects are being destroyed.
Why has copy ctor run? I didn't send a someClass object to a someClass object. Can you explain me the situation?