The below is an exam question:
/* 1 */ string s1 = "FRED";
/* 2 */ string s2 = s1;
/* 3 */ string s3 = "DERF";
/* 4 */ s3 = s1;
For the second and the fourth lines above, name what type of statement that line is. Will
they call the same member function of class string? [5 marks]
So my answer:
- Line 2 is initializing a new string object s2 using the
copy constructorto copy over all the member variables from s1 into the s2. - Line 4 is also copying over all the member variables from s1 into s2, but it is overloading the
assignment operator (operator=)to do so.
Therefore they both are calling 2 different member functions.
Is the above an acceptable answer? Is there anything I can add of do I have the wrong idea?
About your answer regarding Line #4
You cannot be certain that it actually makes use of the copy constructor, and it absolutely shouldn’t.
Why create a temporary object inside
std::string::operator=when you could copy the data froms1intos3directly?What you wrote about
operator=is correct, but leave out what you wrote about the copy-constructor there. There is no initialization of a new object, therefor no constructor should be called.You should also leave out the statement regarding making copies of all the member variables, that doesn’t have to be true.
And when it comes to objects such as
std::stringthere are pointers as members that aren’t copied, but the memory where they point are being copied into a new memory space (to be used by the destination object).Post OP edit of his/hers post..
OP just changed his post deleting what I made a remark on in the first part of this post.