Bloomberg LP Interview Question
Financial Software DevelopersThe line A z = (a = b); is the only one that causes to print right?
So first it prints b and then it prints a (if A& is returned by = operator)
So the answer must be 2 3 1 2.
I do not understand how u guys got 2 2 1 1. Please explain.
If you make overloaded operator= return A& then, the above code will compile and you will indeed get "2211" as output, as marked by gevorg
arun, watchout j is initialized with ii too. i know its duh! but.. thats what they ask for.
Assuming they fix the copy constructor to return a self reference:
A a(1,2);
// 1 is assigned to a.i and to a.j because the constructor only uses the first parameter
A b(2,3);
// 2 is assigned to b.i and b.j
A z = (a = b);
// First, assignment operator is called, which outputs i and j of the passed in parameter (b) but does not change any values. Output is "22" and a reference to a is returned.
// Second, the copy constructor is called which only outputs the 1 and j values of the passed object (a). Output is "11"
// So the total output is "2211"
Assuming they fix assignment operator with A& instead of void
output will be "2222"
Here is complete program and explanation.
struct A
{
int i , j;
A(int ii , int jj) :i(ii),j(ii){}
A(const A&a)
{
cout << a.i << a.j;
}
A& operator = ( A& a)
{
cout <<a.i << a.j ;
return a;
}
};
int main(int argc, char **argv)
{
A a(1,2);
A b(2,3); ==> i and j value will be 2,2
A z = (a = b); ==> Here assignment operator will be called which will print 22. Now 'a' has b's values. then it will call copy constructor to which a object is passed which has value 22 .
}
This wont compile because the operator= returns void. The overloaded operator= has to return a reference to the current object in order for the copy constructor to assign a value to z.
- srini February 26, 2010