-1

I want to add v2 to v1. My member function is working, but free function is not. How can I solve this problem, thanks.

When I compile with: clang++ -std=c++2a hw1.cpp -o hw1 and run with: ./hw1

give 5 as output.

#include <iostream>

using namespace std;

struct Vector3D
{
    int x;
    int y;
    int z;

    Vector3D(int x_, int y_, int z_)
    {
        x = x_;
        y = y_;
        z = z_;
    }

    void add(Vector3D v)
    {
        x = x + v.x;
        y = y + v.y;
        z = z + v.z;
    }

    ~Vector3D()
    {     
    }
};

void add_free(Vector3D v1, Vector3D v2)
{
    v1.x = v1.x + v2.x;
    v1.y = v1.y + v2.y;
    v1.z = v1.z + v2.z;
}

int main(int argc, char const *argv[])
{
    Vector3D v1(1, 2, 3);
    Vector3D v2(4, 5, 6);
    Vector3D v3(7, 8, 9);
    
    add_free(v1, v2);
    v1.add(v2);
    cout << v1.x << endl;
    
    return 0;
}

emir
  • 9
  • 4
  • add_free takes a copy of v1 and v2, so it cannot modify the input parameters. You can use `Vector3D &v1, Vector3D &v2` instead. – jtbandes Dec 01 '20 at 04:58
  • You are modifying a copy, not the object on which the function gets called. I suspect that there is at least one duplicate of this question on SO. – R Sahu Dec 01 '20 at 04:58
  • yes, you are right. thanks. sleepy coding :( – emir Dec 01 '20 at 05:00
  • 4
    Instead of using reference arguments, you could also *return* the new structure. This makes it easier to convert the function into a proper `operator+` overload later. – Some programmer dude Dec 01 '20 at 05:00
  • Very close to being a duplicate. https://stackoverflow.com/questions/8989350/unable-to-change-values-in-a-function – R Sahu Dec 01 '20 at 05:02
  • seems like `add` should be `operator+=` – Ryan Haining Dec 01 '20 at 05:08

1 Answers1

1

You need to pass the Vector3D you'll modify by non-const reference:

void add_free(Vector3D &v1, Vector3D v2)
//                     ^ HERE

Also you can use v1.x += v2.x instead of v1.x = v1.x + v2.x;.

Kostas
  • 3,822
  • 11
  • 28