Reputation: 91
Sorry if this question sounds too basic, but I'd like to know what EXACTLY happens in this code (Point3d
is my own implementation):
int main()
{
Point3d a(1,2,3);
Point3d b(11,12,13);
Point3d c = a+b;
Point3d d = a;
Point3d e;
return 0;
}
So after running the code above, functions are called in the following order:
Point3d (const float x, const float y, const float z) // a
Point3d (const float x, const float y, const float z) // b
Point3d () //since I created a new object in operator+
operator+ (const Point3d& rhs) //a+b
Point3d (const Point3d& rhs) //the copy constructor for d = a
Point3d () //e
I noticed something:
operator=
is never called (However, if I put the assignment and instance declaration in different lines, operator=
is called)Is what I observed above expected? If so, why is operator=
never called?
P.S. my operator+ is returning an object rather than an reference (Point3d rather than Point3d&), I think that's correct?
Upvotes: 0
Views: 49
Reputation: 9
So there's a difference between a copy constructor and an assignment operator. Instances in which you call copy constructor:
object a = b
Instances in which you call an assignment operator:
object a;
object b;
a = b;
Upvotes: 0
Reputation: 598174
- no constructor is called for
c
Most likely due to Return Value Optimization.
operator=
is never called
Because none of the lines shown are performing assignments, only constructions. Use of =
in a line that declares and assigns an object in the same statement is just "syntax sugar" for copy construction.
Point3d c = a+b; // aka: Point3d c(a+b);
Point3d d = a; // aka: Point3d d(a);
However, if I put the assignment and instance declaration in different lines,
operator=
is called
Yes, if separate statements (not lines) are used for declaration and assignment, then operator=
is used.
Upvotes: 3