c++byrefbyval

C++ Programming ( advantages of by ref & by val) query? / methods of editing struct other than byRef


I am going over a mock exam in revision for my test, and one question on the paper confuses me.

Q.)An application is required to pass a structure to a function, which will modify the contents of the structure such that on return from the function call the caller can use the new structure values. Would you pass the structure to the function by value, address or reference?

State clearly why you chose a particular method. Justify your choice by comparing the three methods.

Now I have difficulty understanding this, because I assume the best answer to the question would always be by Ref as that takes the reference pointer of the value and edits its contents rather than just getting a copy. This would be different if using a class based program.

The only other method I would understand would be having a separate value and getting and setting the values, but this would mean extra lines of code, I am a little unsure on what this means, can anyone help enlighten me ? I do not know any other methods to achieve this.


Solution

  • This is not "advanced programming"; it is the absolute basics of C++.

    Whether return-by-value or "out" parameters (implementing using references or pointers) are "best" for any given use case depends on a number of factors, style and opinion being but two of them.

    // Return by value
    //  T a; a = foo(a);
    T foo(const T& in)   // or:   T foo(T in)
    {                    //       {
       T out = in;       // 
       out.x = y;        //          in.x = y;
       return out;       //          return in;
    }                    //       }
    
    // Out parameter (reference)
    //  T a; foo(a);
    void bar(T& in)
    {
       in.x = y;
    }
    
    // Out parameter (pointer)
    //  T a; foo(&a);
    void baz(T* in)
    {
       in->x = y;
    }
    

    The question is asking you what the pros and cons are of these three approaches.