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

Asked

Viewed 307 times

2

I took 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 method void setNome(const string &nome);?

  • If I’m not mistaken, public class Pessoais not valid C++ ...

1 answer

4


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

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

What you can do is force a parameter to receive a pointer, probably 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 the &. Thus the reference is the value.

Nothing prevents you from creating the method without the reference, but copying all the data into the method can be very costly. This goes for 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, can generate a high cost in the passage of data.

Some compilers do optimizations for string and avoid the cost of copying the entire structure. But you cannot count on this if the performance is important in any scenario. In new versions C++ uses a reference with semantics of move explicit and ensures optimization.

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

Additional recommended readings:

  • Well, I’m studying Object Orientation with C++, as you can see, since I used this language as an example. I find it much more intuitive to understand the concepts of OO, since I failed other.

  • But answering your question, I saw an example using an integer and I thought with string it would also be the same way. I’ve always had this question of whether I should use reference or not.

  • Then the void method setName(const string &name); would be empty setName(string name); ?

  • A int is a type naturally by value and small, I see no reason to use a reference in this case. That is, the question starts from a wrong premise. Perhaps she should have shown what she saw, what she intends and try to understand within the contact presented. A loose example like this doesn’t help much in this case. In this example I wouldn’t use the reference. If it were a int probably would not use, but it depends on the context. In the example for without a string has the chance of the reference to give a better performance in some cases.

  • Thank you so much for everything!

Browser other questions tagged

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