PDA

View Full Version : Quick C++ question


ZeekLTK
09 Dec 2005, 12:57 PM
I have a function that takes these arguements:

void aFunction(vector<tclass>, gclass&, gclass&, gclass&, gclass&, gclass&, gclass&, gclass&, gclass&)

In the function I create a vector<gclass> and store all 8 inputted gclasses into it. Then I have a loop which goes through the vector and makes (different) changes on each class one at a time.

The function does exactly what it is suppose to, and makes all the changes correctly... but then when the function ends, it does not save any of those changes and my gclasses are exactly the same as they were before I put them into the function!

It's probably something stupid I am overlooking, but I can't figure it out at the moment. So, how do I make my function save the changes it makes to the classes that I inputted into it??

I have tried inputting them with and without the '&' sign on the end, neither works.

Thanks in advance!

Foosinho
09 Dec 2005, 01:26 PM
The STL container "vector" is likely making copies of the gclass objects you are putting into it. You can store pointers to the gclass objects in your vector (with all of the associated dangers of working with pointers), or IIRC you can store a reference (ie, vector<&gclass>). I know the pointer option works, and I'm pretty sure the reference option works. Unfortunately, I'm no longer at the job where I did something exactly like this, so I can't reference my source code to see which I chose and why.

Also, if your class creates the vector, why is it being passed in as a variable? Without a reference operator as well?

JeffS
09 Dec 2005, 02:20 PM
I think you need the & operator with the vector parameter. Otherwise, it's passing by copy, rather than by reference. When it does this, the vector copy only has scope with in the function, and is not copying data to the original vector that was provided in the function call.

I could be wrong - it's my best guess. But it's how I understand C++'s pass by value and pass by reference conventions.

MikeLastort2
09 Dec 2005, 02:22 PM
Yep, you're passing a copy instead of the class instead of the class itself.

The prototype should be something like this

void aFunction(vector<&tclass>, gclass&, gclass&, gclass&, gclass&, gclass&, gclass&, gclass&, gclass&)