-5

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.

RNewell122
  • 128
  • 10
  • What is a "reference pointer"? – Lightness Races in Orbit Jan 18 '16 at 14:16
  • At least two of the given alternatives can achieve this. I would suggest that you study more about the three methods mentioned until you can answer this confidently. (Unfortunately, the answer is to some extent a matter of taste, so the correct answer depends on your teacher.) – molbdnilo Jan 18 '16 at 14:16
  • 1
    Lingo notes: "reference pointer of the value" should be "reference to the object". There are no "reference pointers", and you can't point to, or reference, a value. It's important to get the terminology right, otherwise you'll end up answering the wrong question or misunderstanding it. – molbdnilo Jan 18 '16 at 14:17
  • Thanks for the clarification. – RNewell122 Jan 18 '16 at 14:19

1 Answers1

0

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Its what our uni call the module, what they mean is its a step up from the 1st year programming module which is mainly algorithms. – RNewell122 Jan 18 '16 at 14:19