How is the C ++ reference?

Posted on

Question :

class Data {

int d, m, a;

  void inic(int dd, int mm, int aa);
  void soma_ano(int n);
  void soma_mes(int n);
  void soma_dia(int n);


void timewarp(Data& d)

As far as I understand the variable d is of a type defined by the programmer, that is, a class. But what does this & in Data& mean?

Is it a recursion?

I’m breaking my head to understand this parameter passing.


Answer :

The d parameter of the timeward method is a reference to an object of type Data defined in the application.

Note that there is a member named d inside type Data , which can not be confused. That’s why more significant names would be better.

Nothing to do with recursion. It’s a lot simpler.

By the title you already have a notion of what it is. In this case you will receive a reference for argument passed to this method. That is, the method will get a pointer to the object, but all access to the object will be done naturally, you will not have to treat the pointer, the compiler will treat it for you.

When the method is called the passed argument will be a value of type Data . Something like this:


Internally should the method do something like this:

d.soma_ano(1); //está somando 1 ano no dado

At the end of the run the last argument will have one more year because as it was passed by reference, any change in the parameter will reflect on the argument, after all it is manipulating the same referenced object.

If the declaration were simple, the passage of the parameter would be done by copy, that is, the data of the argument would be copied in the argument. In addition to this being potentially slower (not much in this particular case), at the end of the operation, there would be a discard of the information, since any change would be made to the copy of the object and not to the original object.

Leave a Reply

Your email address will not be published. Required fields are marked *