• Advertisement
Sign in to follow this  

Issues with class

This topic is 3646 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.
#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;
	}
}



Does anybody know why this->x and this->y change inside the member function, and how to prevent it? Thank you, -Zael-

Share this post


Link to post
Share on other sites
Advertisement
What is the unexpected output? I believe your program has undefined behavior. When you add elements to a vector, the vector can be resized. This invalidates all of the old elements in the vector, because a new, larger memory block was allocated and all of the old elements were copied to it. A method of an object should not alter the container the object is stored in, unless you're absolutely sure you know what you're doing, and even then the design is probably flawed.

Share this post


Link to post
Share on other sites
Ah. Thank you. I did not realize that by resizing, older elements became invalid... That would explain the seemingly random nature of some of the output. I guess I'll try to implement that function by another means.

-Zael-

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement