class attribute read-only issue

My header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef OBJECT_H
#define OBJECT_H
#include <vector>
using namespace std;

class Object
{
    public:
        Object();
        void update(Object obj);
        void setVelocity(vector<double> v);
        virtual ~Object();
    protected:
    private:
        vector< double > velocity;
};

#endif // OBJECT_H 

My class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "Object.h"
#include <gl/gl.h>
#include <cmath>
#include <iostream>

Object::Object()
{
    //ctor
    velocity.resize(2);
}
void Object::setVelocity(vector<double> v)
{
    velocity = v;
}
void Object::update(Object obj)
{
        obj.velocity[0] = -10.0;

        vector<double> vec (2);
        vec[0] = -10.0;
        obj.setVelocity(vec);
}

Object::~Object()
{
    //dtor
}

It can read velocity's value, but I can't seem to change it from within the method. I tried directly changing the value (in the update method) and I tried passing in a value through the setVelocity method. I didn't get any errors, but the code doesn't seem to do anything. How can I change its value?
How do you expect to use the code? Why does update modify a different object?
I don't think that that is relevant, but the update method will modify velocity from both the object it is called on and the object passed in by the parameter.
By changing, you mean through the Object::update(Object) method? Because your Object::setVelosity(vector<double>) method works. However, even though it works, you are passing something that is not a base type and can be expensive as you are passing by value (i.e. the vector<double> is being copied). You probably want to pass by a const reference instead.

As for the update() function, you are again passing by value. The object passed will be copied and any operations done to it will be discarded at the end of the function scope. If you want the results to be seen from the caller's side, you have to pass it as a reference.
Topic archived. No new replies allowed.