0

I realize that these may be beginner questions, but to properly understand concepts, I'd appreciate solid answer or a link towards documentation.

What is the meaning of & or * in front of parameter names, or after datatypes within C++ functions?

For example:

void ApplicationUI::requestFinished(QNetworkReply* reply) { //... }

or

void PostHttp::post(const QString &body) { //... }

Bonus question In the post function above... does const make it required for this function pass constant variable or is there a different reason for it?

ST3
  • 8,826
  • 3
  • 68
  • 92
iboros
  • 317
  • 2
  • 5
  • 15

2 Answers2

8

In the first example (*) you are passing a pointer to your function and in the second example (&) you are passing a reference.

To know the difference between both, read this post : What are the differences between a pointer variable and a reference variable in C++?

Bonus question :

One of the major disadvantages of pass by value is that all arguments passed by value are copied to the parameters. When the arguments are large structs or classes, this can take a lot of time. References provide a way to avoid this penalty. When an argument is passed by reference, a reference is created to the actual argument (which takes minimal time) and no copying of values takes place. This allows us to pass large structs and classes with a minimum performance penalty.

However, this also opens us up to potential trouble. References allow the function to change the value of the argument, which in many cases is undesirable. If we know that a function should not change the value of an argument, but don’t want to pass by value, the best solution is to pass by const reference.

You already know that a const reference is a reference that does not allow the variable being referenced to be changed. Consequently, if we use a const reference as a parameter, we guarantee to the caller that the function will not (and can not) change the argument!

Community
  • 1
  • 1
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
3

* means that parameter is a pointer and & is passing by reference

janisz
  • 6,292
  • 4
  • 37
  • 70