Bloomberg LP Interview Question
Software Engineer / DevelopersFor the second case, I think you are talking about 1 instead of 3. Because "=" is called.
No... the assignment operator will be called to assign a to c. In this context the value of 2 contained in c.x will be overwritten by the value of 4 contained in a.x. This new value will then be decremented to 3. I suggest you compile and run the following example
#include <iostream>
using namespace std;
// Online Test
class Someclass {
public:
int x;
public :
Someclass(int xx) : x(xx) { }
Someclass(const Someclass& a) { x = a.x ; x++;}
Someclass& operator =(const Someclass& a1) { x = a1.x ; x--;}
};
int main( )
{
Someclass a(4);
Someclass b = a;
Someclass c(2);
c = a;
cout << "a.x = " << a.x << endl;
cout << "b.x = " << b.x << endl;
cout << "c.x = " << c.x << endl;
}
"=" is such a b*tch! :)
I actually compiled your (dfmcia) program. You are right-
b.x =5. I expected b.x=3.
You said for "=" operator either the copy or assignment constructor is called, but i always got b.x=5 when I ran the program multiples. How do i make sure only assignment operator is called when "=" is used, given that both of them are defined?
first, there is an unclosed comment (/*) so it won't compile.
Second, There will be no output, because there is no output line.
Third, a.x = 4 because the instantiation of a uses the constructor that takes an int. b.x = 5 because the instatiation of b uses the copy constructor; the call:
SomeClass b = a;
is equivalent to
SomeClass b(a);
Both use the copy constructor. The assignment operator would only be called with:
SomeClass b;
b = a;
class Someclass {
public:
int x;
public :
Someclass(int xx) : x(xx) { }
Someclass(const Someclass& a) { x = a.x ; x++;}
Someclass& operator =(const Someclass& a1) { x = a1.x ; x--;}
};
int main( )
{
Someclass a(4);
Someclass b = a;
Someclass c(2);
c = a;
cout << "a.x = " << a.x << endl;
cout << "b.x = " << b.x << endl;
cout << "c.x = " << c.x << endl;
}
Um... actually the answer is:
- Wandering programmer February 28, 2010b.x = 5
because in this case, the copy constructor is called. In no case could the result be 4 since "=" symbol forces either the copy constructor or the assignment operator to be invoked. The statements
Someclass c(2);
c = a;
will give the result 3, not 4 because the assignment operator will be called rather than either of the constructors.