Original Post
Hello, I'm currently writing a program, and am having an issue with a class I wrote. I think the issue likely has something to do with the deeper parts of classes I haven't learned yet, but it might be a stupid mistake too. I have a class, and one member function of the class takes a vector of that class as a parameter, and adds to it. In the program I wrote entirely new objects are added to the vector. The sample program I have below basically copies the first element into subsequent elements, but after the first push_back() is called from within the member function the x and y seem to change for the current element. The weirdest thing for me is probably that x, and y return to their original values after the member function is completed. Does anybody know why this->x and this->y change inside the member function, and how to prevent it? Thank you, -Zael-
#include <vector>
#include <iostream>
using namespace std;
class test
{
private:
int x, y, type, age;
public:
test(int, int, int);
void turn(vector <test> &);
};
test::test(int x1, int y1, int t)
{
x=x1;
y=y1;
cout <<"making x " << x<<endl;
cout <<"making y " << y<<endl;
cout <<"making t " << t<<endl;
type=t;
age=0;
}
void test::turn(vector <test> &lotsoftest)
{
if(age>2)
{
for(int i=0; i<5; i++)
{
test blue(x, y, type);
lotsoftest.push_back(blue);
cout << "X: "<<x<<endl;
cout << "Y: "<<y<<endl;
cout << "Type: "<<type<<endl;
}
}
age++;
}
int main()
{
int x, y;
cout << "X?\n";
cin >> x;
cout << "Y?\n";
cin >> y;
cout << "Starting...\n";
vector <test> lotsoftest;
char c;
test tmp(x, y, 1);
lotsoftest.push_back(tmp);
while(c!='a')
{
for(int i=0; i<lotsoftest.size(); i++)
{
lotsoftest.turn(lotsoftest);
}
cin >> c;
}
}