I am very new to c++ and just started to learn operator overloading. Here is my attempt
class Vector
{
public:
float x=0,y=0,z=0;
Vector(float x, float y, float z) :x(x),y(y),z(z) {}
Vector(Vector& copy) :x(copy.x),y(copy.y),z(copy.z){ std::cout << "Copy Created" << std::endl;} //Testing if any new objects were created during the operator overloading process[For my purpose this should not be called as no new objects should be created except than the returned result of each operator]
public:
Vector& operator+(Vector& v1) //return this+v1
{
Vector v(this->x+v1.x,this->y+v1.y,this->z+v1.z);
return v;
}
Vector& operator-(Vector& v1) //return this-v1
{
Vector v(this->x - v1.x, this->y - v1.y, this->z - v1.z);
return v;
}
Vector& operator*(Vector& v1) //return this cross v1
{
Vector v(this->y * v1.z-this->z * v1.y, -this->x * v1.z + this->z * v1.x, this->x * v1.y - this->y * v1.x);
return v;
}
}
std::ostream& operator<<(std::ostream& output, Vector& v)
{
output << v.x << "," << v.y << "," << v.z << std::endl;
return output;
}
int main()
{
Vector
v1(1, 2, 3),
v2(4, 5, 6);
Vector
v3 = v1 + v2,
v4 = v1 - v2,
v5 = v1 * v2;
std::cout << v3 << v4 << v5;
return 1;
}
All 3 vectors when printed have garbage values and the copy constructor was invoked 3 times for each operation. I have passed each of the vectors by reference but still an new temporary instance was created somewhere i don't understand.
I have also tried adding the keyword const to both the operators and their parameters as was suggested by previous threads but it didn't solve the problem
Since i am a novice an elaborate explanation of the solution would greatly be appreciated. Thank you