The following output is not clear to me. Why in the first case output is: Joni Gallo, while in the second case (after I changed only one line), output is: Jonlo
Output of this:
// classes and default constructors #include <iostream> #include <string> using namespace std; class Example3 { string data; public: Example3 (const string& str) { data = str; // data.erase(3,5); } Example3() {} void doit() { data.erase(3,5); } const string& content() const {return data;} }; int main () { Example3 foo("Joni Gallo"); Example3 bar (foo); bar.doit(); cout << "content: " << foo.content() << '\n'; return 0; } is Joni Gallo, while output of this:
// classes and default constructors #include <iostream> #include <string> using namespace std; class Example3 { string data; public: Example3 (const string& str) { data = str; data.erase(3,5); } Example3() {} void doit() { // data.erase(3,5); } const string& content() const {return data;} }; int main () { Example3 foo("Joni Gallo"); Example3 bar (foo); bar.doit(); cout << "content: " << foo.content() << '\n'; return 0; } is: Jonlo
? Why? Why erase affected the original object in the second case, but not in first?
PS Also what does passing const string& str in constructor and then assigning it to member variable mean - does it mean everytime I change the member variabe content the original objects contents (whose reference was passed to the constructor) will also be changed? (like it would be with pointers)
erase'd in the original object's string in its constructor, so of course it modified it.barwhile you printfoo::datathat's unchanged. In the second case infooconstructor you changedata.fooerases its own string in its constructor.