I have the below code and I am trying to simply assign an integer (for testing purposes) to a variable inside a struct, which itself is inside of a class. I am not sure what I am doing wrong, but it seems that I am getting a new instance of the struct every time I try and access it from the same (already declared) class.
I feel like I am missing something obvious.
Anyways, in the program output, I entered the number '1337' and you can see that before I call the function to store it, it has been initialized to 0, but after it simply resets the value to 0.
Hopefully my question makes sense, or will be clear from the output. Thanks!
"scheduler::addToQueue( )" is where you're going wrong. The first formal parameter declaration states that the actual parameter that will be given to it will be copied. Therefore, the first formal parameter of "scheduler::addToQueue( )" will be working with a copy, and the changes made to the actual parameter will be local to the actual parameter. For instance:
1 2 3 4 5 6 7 8 9 10
void function(int param)
{
param += 2;
}
int main( )
{
int value(0);
function(value);
}
In this code, "function( )" accepts an "int" as an actual parameter. During the call to "function( )", "value" is passed to it; "value" is in fact copied into "param" of "function( )". Changes to "param" will affect only "param" and not "value". This is known as passing-by-value.
To overcome this, we use references:
1 2 3 4 5 6 7 8 9 10
int function(int ¶m)
{
param += 2;
}
int main( )
{
int value(0);
function(value);
}
In this code, "value" is passed-by-reference. When "function( )" is called, "param" of "function( )" will refer to the actual parameter ["value"]. Any changes made to "param" will affect "value".
See here for more: http://www.cplusplus.com/doc/tutorial/pointers/#reference