I study C ++ according to the book by S.Prat, an example taken from the book. A class is defined with the following function:

const Stock & Stock::TopVal(const Stock & _st) const { if (_st.total_val > total_val) return _st; else return *this; } 

Now in main() create an array of Stock type objects and assign the value of one of the array elements to the top pointer:

 for (int st = 1; st < STKS; st++) { top = &top -> TopVal(stocks[st]); } 

Explain why when assigning a top value from the TopVal function, TopVal should specify the link sign, because the link is already passed from the function?

    2 answers 2

    The link is passed from the function, but the link is like a pseudonym, not an address. Those. if you have

     int x; int& r = x; int* p = &x; 

    then r - note, initialized by x , and not by the address, like a pointer. How exactly the link is internally implemented - in this case does not matter.

    You use r instead of x - for example, in the assignment r = 5; . B exactly the same way you get the address through the link - p = &x identically p = &r; .

    A direct link to the pointer is not converted, and therefore you need an address operator for the returned link.

      In this sentence

       top = &top -> TopVal(stocks[st]); ^^^ 

      The address operator used is & . In C ++, many characters are overloaded and have several meanings depending on the context. Thus, for example, the * symbol can mean a binary multiplication operator, a pointer dereference operator, and be used in declarations to declare a pointer.

      In turn, the & symbol can mean an address taking statement, as in the program you cited, a link when declaring links, as well as a binary bit AND operator.

      So, in this declaration, the member function

       const Stock & Stock::TopVal(const Stock & _st) const ^^^ ^^^ { if (_st.total_val > total_val) return _st; else return *this; } 

      symbol & used to advertise links. The function returns a reference to an object of type const Stock , and also declares as a parameter a reference to an object of such type const Stock .

      And in this sentence

       top = &top -> TopVal(stocks[st]); ^^^ 

      top , which is most likely declared as

       const Stock *top; 

      the address of the object, the link to which is returned from the function, is assigned.

      To make it clearer, consider the following example.

       int x = 10; int &r = x; int *p = &x; r = 20; *p = 30; 

      In this example, the reference r declared to the object x and the pointer p , which will contain the address of the object x . A link can be considered as an alternative object name - as an object alias. You can refer to the memory area where the object x is located by the original name x , or by using the name r .