I’m writing a math library as a practical exercise. I’ve run into some problems when overloading the = operator. When I debuged it, I noticed that the call to vertex1 = vertex2 calls the copy constructor instead.
In the header file I have:
//constructors
vector3();
vector3( vector3 &v );
vector3(float ix, float iy, float iz);
//operator overloading
vector3 operator =(vector3 p);
....
In the source file I implemented:
vector3 vector3::operator =(vector3 p)
{
vector3 v3;
v3.x = p.x;
v3.y = p.y;
v3.z = p.z;
return v3;
}
Later on I have a crossproduct method, and I want to use it like so:
vector3 v3;
v3 = v1.crossProduct(v2);
The error message is:
error: no matching function for call to `vector3::vector3(vector3)’
but I do not want to call the copy constructor.
There are mistakes in your code. Your copy-constructor must take a
const&. The reference will avoid making a copy (which you wouldn’t be able to do, being the copy-constructor), and it should beconstsince you’re not modifying it:Temporary variables can be bound to
const&, but cannot be bound to a mutable reference. That is, with your code you could do:but not:
Additionally, your
operator=is incorrect. Like the copy-constructor, it should generally take aconst&, but it should return a reference tothis. That’s how chaining works:Returning a temporary is unorthodox, and doesn’t accomplish anything. In your case, you could assign over and over and never change the value. Weird:
operator=needs to changethis.