Why in set methods in C ++ do I have to use the parameter as a reference?

2

I have taken this class Pessoa as an example:

public class Pessoa{
private: 
     string nome;

public:
     string getNome();
     void setNome(const string &nome);
};

My question is: why should I use a parameter by reference in the void setNome(const string &nome); method?

    
asked by anonymous 28.08.2016 / 01:02

1 answer

3

For the same reason you have to use it in any other type of method. Or should not use in any method. Let's understand.

Data is passed to the parameter by value, so the value of the argument is copied to the variable that represents the parameter. Always.

What you can do is force a parameter to receive a pointer, probably by creating a reference to the value you want to manipulate within the method. One of the ways to do this is to determine that the parameter is a reference, through & .

Nothing prevents you from creating the method without the reference, but copying all the data into the method can be very costly. This applies to any method without distinction.

In this case it may be interesting to use the reference since a string is passed by value and is very large, which can generate a high cost in passing the data.

Some compilers make optimizations for string and avoid the cost of copying every structure. But you can not count on this if performance is important in any scenario.

Now I return the question, why do you think you have to do this? If you read somewhere, they taught wrong or did not understand the context.

Additional readings recommended:

28.08.2016 / 01:26