Ctor + overloading =

hey,

if I have defined
* the copy constructor in my class
* and also implemented my '=' operator. what will happened if:
1
2
3
4
5
6
int main(){
A a1(1),a2;
a2 = a1;          // who is going to be called?

return 0;
}


in line"a2 = a1;" who is going to be called? the copy constructor or the operator that overloaded?
explanation please.
thanks
The assignment operator.

The copy constructor is only called when the object is constructed. This happens once and only once, when the object is declared (or allocated with new):

1
2
3
4
// your example:
A a1(1);  // a1 is constructed
A a2;  // a2 is default constructed
a2 = a1;  // assignment operator 


If you assign in the same command as the definition, then the object is being copy constructed:

1
2
A a1(1);  // a1 is constructed
A a2 = a1;  // a2 is copy constructed (no assignment operator) 


Even though we're using = in the 2nd example, the assignment operator is not called. This is because a2 is being defined, and therefore is being constructed.

The assignment operator can only be called after the object is constructed.
Topic archived. No new replies allowed.