0

I wrote the folloing code to test how to change values of class object in a function.

using namespace std;

class test{
public:
    int a;
};

void runer(test testXX){
    testXX.a=10;
}

int main()
{
    test test1;
    test1.a=5;
    runer(test1);
    cout<<test1.a;
    return 0;
}

When I run the following code the output is 5 and not 10. Is it because I can't change the values of class instances, like I can't change the values of array members without using pointers? I would be grateful if someone could clarify that!

GraphLearner
  • 179
  • 1
  • 2
  • 11

3 Answers3

1
void runer(test testXX){
    testXX.a=10;
}

Takes a full copy of the type test, so it is modified in the function, but a different instance to the one in main.

Parameters in C++ are sent by value. The simplest example which makes sense is

 int function( int value ) {
      for( ; value > 0 ; value-- ){
          cout << "Hello\n";
      }
 } 

 int main( int , char ** ){
       int value = 10;
        function( value ); // display 10 things
        function( value ); // display 10 things again (not modified).
        function( 5 );  // also not making sense, if parameter is modified.
 }

To allow objects to be modified, they need to be sent as references, or pointers. This allows the value of the item to be changed. The literal 5 can not be sent to a function expecting a reference.

void runer(test & testXX){
    testXX.a=10;
}

Now the same object is sent from main to runner, and modifications are done to the single object.

mksteve
  • 12,614
  • 3
  • 28
  • 50
1

You are passing the argument to the function by value, so it gets a local copy that only lives as long as the scope of the function.

If you want the function to be able to modify the original object that you pass in, then pass it by non-const reference void runer(test& testXX) .

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
0

Your code makes a call by value. Hence, the change doesn't appear in the actual object. To change the value of the attribute of the object you need to make a call by reference.

void runer(test &t){
    t.a = 10;
}