So I have a class Scene
which contains a vector of elements of another class ´Object´. Now, in my main() I want to make changes to an Object, and this must be also applied to the instance of the object inside the Object vector in the class.
My idea was to create a function that puts the object inside the vector, and returns a reference to it, so that from the main you can change it and make changes affect the vector. It works perfectly with just one object. The problem is that, if I use more than 1 object, it just stops working, and none of the objects changes its position, not even the first one that used to work before. What's the problem? Is there a better way to do this (I'm new to c++ hehe)
Thanks!
My code is this:
class Object{
private:
int posX, posY;
string name;
public:
Object(){
name = "Object" + id;
}
int getPositionX(){
return posX;
}
int getPositionY(){
return posY;
}
void setPosition(int positionX, int positionY){
posX = positionX;
posY = positionY;
}
};
My scene class:
class Scene{
private:
vector <Object> objectsInScene;
public:
Scene(){
cout << "Scene created";
}
vector <Object> getObjectsInScene(){
return objectsInScene;
}
Object& insertObject(Object newObject){
objectsInScene.push_back(newObject);
return objectsInScene[objectsInScene.size()-1];
}
};
and my main:
int main(){
Scene mScene;
Object myObj;
Object secondObj;
secondObj.setPosition(15,15);
myObj.setPosition(7,7);
Object& myObject = mScene.insertObject(myObj);
Object& secondObject = mScene.insertObject(secondObj);
//other things
switch(cin.get()){
case 'w':
myObject.setPosition(3,3);///This is the one that doesn't work
break;
}
}