GE (General Electric) Interview Question
Senior Software Development EngineersTeam: HCT-I
Country: India
Interview Type: In-Person
Correct answer is that assignment operator will be used in that case - default one generated by compiler or provided by "sample" class designer.
Persons who say that copy constructor would be invoked in that case are wrong. Constructor is supposed to *construct* object and in presented scenario both objects - pointed by s1 and s2 - are already created.
Copy constructor would be called in such scenario:
sample *s1 = new sample();
// here is called copy constructor
sample s2 = *s1;
// also here
sample *s3 = new sample(s2);
// but here is called assignment operator since *s3 was already crated
*s3 = *s1;
as per my understanding, it will call when we do
{
s1 = s2;
}
please explore more ..i am not getting clear picture of this concept.
The answer is correct. s1 = s2 would make the pointer s1 point to the same thing s2 points to. This is different from copying the object (invoking the copy constructor), which is achieved by *s1 = *s2. Often people are confused about this topic if they don't understand the difference between objects themselves and pointers to objects -- there is a very big difference, though! I recommend reading a tutorial on pointers if you don't understand this distinction.
The question says answer in detail, so in detail:
- Anonymous December 10, 20131: s1 will be dereferenced
2: s2 will be dereferenced
3: the assignment operator will be called on the dereferenced s1 with the dereferenced s2 as the parameter