confusing syntax | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

confusing syntax

Hi Always for passing a reference to the function we used this syntax ``` void foo(myclass *par){ cout << par->att <<endl; } ``` with * operator in parameter definition. but in the operator overloading I can see & oprator instead like the following ``` MyClass operator+(MyClass &obj) { MyClass res; res.var= this->var+obj.var; return res; } ``` what does & operator in parameter definition means? and why we accessed the obj attributes with dot operator if it is pointer? shouldn't it be -> ?

22nd Mar 2017, 10:49 PM
Yousof Ebneddin Hamidi
Yousof Ebneddin Hamidi - avatar
1 Answer
0
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp4_PointerReference.html C++ added the so-called reference variables (or references in short). A reference is an alias, or an alternate name to an existing variable. For example, suppose you make peter a reference (alias) to paul, you can refer to the person as either peter or paul. The main use of references is acting as function formal parameters to support pass-by-reference. In an reference variable is passed into a function, the function works on the original copy (instead of a clone copy in pass-by-value). Changes inside the function are reflected outside the function. A reference is similar to a pointer. In many cases, a reference can be used as an alternative to pointer, in particular, for the function parameter. 2.1 References (or Aliases) (&) Recall that C/C++ use & to denote the address-of operator in an expression. C++ assigns an additional meaning to & in declaration to declare a reference variable. The meaning of symbol & is different in an expression and in a declaration. When it is used in an expression, & denotes the address-of operator, which returns the address of a variable, e.g., if number is an int variable, &number returns the address of the variable number (this has been described in the above section). Howeve, when & is used in a declaration (including function formal parameters), it is part of the type identifier and is used to declare a reference variable (or reference or alias or alternate name). It is used to provide another name, or another reference, or alias to an existing variable. The syntax is as follow:
23rd Mar 2017, 12:03 AM
Yousof Ebneddin Hamidi
Yousof Ebneddin Hamidi - avatar