What is the reference of C++?

Asked

Viewed 199 times

4

class Data {

int d, m, a;
public: 

  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)
{
}

From what I understood the variable d is of a type defined by the programmer, that is, a class. But what this means & in Data&?

It is a recursion?

I’m racking my brain to understand this parameter crossing.

  • There’s some weird stuff in the code, but let’s go in pieces :)

1 answer

3


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

Note that there is a member called d within the type Data, which cannot be confused. Therefore more significant names would be better.

Nothing to do with recursiveness. It’s something much simpler.

By the title you already have a sense of what it is. In this case you will receive a reference to the argument passed to this method. That is, the method will receive 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 handle it for you.

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

timewarp(data);

Internally the method will do something like this:

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

At the end of the execution the last argument will have an extra 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 statement was simple, the passage of the parameter would be done by copy, that is, the argument data would be copied in the argument. Besides being potentially slower (not much in this specific case), at the end of the operation, there would be a discard of the information, since any change would be made in the copy of the object and not in the original object.

  • Now I get it. The variable (Date & d) changes the superscript object type Date and not a copy of how in (Date d).

  • 3

    We can say that a reference is a pointer that can never be null (the compiler more positively ensures that a reference is valid). Otherwise a reference has the same advantages as the pointer (save a copy of the object and polymorphism - accept subclass objects)

  • void timewarp(Data &d) in C++ would be the equivalent of passing the memory address of a variable in the C language ?

  • 1

    @Rogi93.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.