Why is the copy constructor not called in this sample program?
When the function input()
returns an object, a copy of the object is made, but I cannot see that the copy constructor is called according to the output in the console.
Output:
Enter a string: ssssssssss
ssssssssss
Freeing s
Code:
#include <iostream>
using namespace std;
class Sample {
char *s;
public:
Sample() { s = 0; }
Sample(const Sample &sample) { cout << "copyconstructor\n"; }
~Sample() { if(s) delete[] s; cout << "Freeing s\n"; }
void show() { cout << s << "\n"; }
void set(char *str) {
s = new char[strlen(str) + 1];
strcpy(s, str);
}
};
Sample input() {
char instr[80];
Sample str;
cout << "Enter a string: ";
cin >> instr;
str.set(instr);
return str;
}
int main() {
Sample ob = input();
ob.show();
return 0;
}