c++cinder

C++ (cinder): Can't update objects' properties in keyDown function


I have a vector of Shapes, Shape being a class I wrote. In the keyDown function, I iterate through this vector of Shapes and update the bool property, background, to true. However, it appears not to be persisting this change.

Main class:

vector<Shape> mTrackedShapes;

void CeilingKinectApp::keyDown( KeyEvent event )
{
    // remove all background shapes
    if (event.getChar() == 'x') {
        for (Shape s : mTrackedShapes) {
            s.background = true;
        }
    }
}

Shape.h

#pragma once
#include "CinderOpenCV.h"
class Shape
{
public:
    Shape();

    int ID;
    double area;
    float depth;
    cv::Point centroid; // center point of the shape
    bool matchFound;
    bool moving;
    bool background;
    cinder::Color color;
    int stillness;
    float motion;
    cv::vector<cv::Point> hull; // stores point representing the hull of the shape
    int lastFrameSeen;
};

Shape.cpp

#include "Shape.h"

Shape::Shape() :
    centroid(cv::Point()),
    ID(-1),
    lastFrameSeen(-1),
    matchFound(false),
    moving(false),
    background(false),
    stillness(0),
    motion(0.0f)
{

}

It registers the keyDown event, and correctly iterates through the vector, but the background property remains false. What am I doing wrong?


Solution

  • Try

     for (Shape &s : mTrackedShapes)
    

    Your code would make a copy of the object, and you would change the properties on the copy rather than the one in the vector