The following code prints:
2
1
instead of
2
2
Why is my setter not adjusting the value?
Main
Vector location = camera.get_location();
camera.get_location().set_y(location.get_y() + 1);
std::cout << location.get_y() + 1 << std::endl;
std::cout << camera.get_location().get_y() << std::endl;
camera.h
#ifndef CAMERA_H
#define CAMERA_H
#include "vector.h"
class Camera {
private:
Vector location;
public:
Vector get_location();
void set_location(Vector);
};
#endif
camera.cpp
#include "camera.h"
Vector Camera::get_location() { return location; }
void Camera::set_location(Vector l) { location = l; }
get_locationreturns a copy of the original object. Soset_ydoes modifyybut it is modiying the copy of the original location. If you want the above to work as you expect, then return reference:The function-body will be same as before:
Now it will work the way you expected.
You could write the code as:
It modifies the
camera‘s location object.Compare the above code with this:
It does NOT modify
camera‘s location object! It modifies the copy, not the original.Hope that helps.