There is a function with a signature:

void some_func(Object &object); 

As the only parameter, it takes a link. Create a pointer:

 Object *pObj = new Object(); 

The next step, it is logical suggests that we should pass the link to the upper function, that is:

 some_func(&pObj); 

But the compiler does not accept this option, but accepts this:

 some_func(*pObj); 

Question: As I understood earlier, the operator * is a dereference operator and if we pass *pObj , then we pass the contents of the link to the function some_func .

  • Why does the pointer version work that way?
  • Why can't we pass a link to a method with such a parameter? (&rObj)
  • What happens when some_func(*pObj) ? According to my guesswork, is a copy of the content object created by a pointer reference and then passed as a parameter to a method?
  • 2
    Why did you decide that &rObj is a link? - AnT 10:02 pm
  • But isn't the textbook detailing everything about it? ... - AR Hovsepyan
  • @ARHovsepyan, even Straustrup has not described this point. Apparently, the maestro, considered it self-evident. - German Borisov
  • @Herman Borisov, I studied the language completely independently and it was from the Starruprup books. And believe that I have not had such questions. Do it yourself why ... you just need to study, not read. - AR Hovsepyan
  • 3
    @AR Hovsepyan * Strastrup. The textbooks are told, and you are right that if you study , then such questions most likely should not arise. However, the author had such a question, and it’s not at all bad. To ask a question is always good. For you, the answer may be obvious, for the questioner - no. And it’s better to answer, to share knowledge, than to send some abstract textbook to read (even then a specific title and author would be given). Such comments are not useful, but only discourage the desire to learn the language and ask questions on this resource. - Vlad Sivirin

4 answers 4

Token &

In C ++, this token has many meanings:

  • As a binary operator, the operator is a bitwise "and".

     0b0011 & 0b0110; // 0b0010 
  • As a unary operator, the operator takes the address of a variable.

     Type a; Type * ap = & a; // указатель на переменную типа Type 
  • As part of the type declaration of a type modifier.

     Type & r; // ссылка на переменную типа Type 

Token *

This token has the same set of values.

  • As a binary operator - the multiplication operator.

     3 * 5; // 15 
  • As a unary operator, the dereference operator (taking the value) of a variable.

     Type a; Type & ar = * a; // ссылка на переменную типа Type 
  • As part of the type declaration of a type modifier.

     Type * r; // указатель на переменную типа Type 

References as values

Working with links is like working with their values. You cannot override a link to point to another object. Almost the entire syntax for the link and for the variable values ​​are the same. Links are branded as Type & name . And in the future, behave like ordinary permenenye containing value.

 struct Type { int a; } Type o; Type & r = o; oa = 1; // ok ra = 2; // ok 

The reference variable can be assigned to the object and vice versa:

 Type & ref = o; Type val; ref = val; val = ref; 

Passing as an argument to a function is also an assignment, so the previous one is also true for them:

 void fun1(Type x) {} fun1(o); // ok fun1(r); // ok void fun2(Type & y) {} fun2(o); // ok fun2(r); // ok 

Why can not assign pointer reference.

One of the most important reasons for this is that the pointer may contain the address of a non-valid object. This process is given to programmers:

 void funcp(Type* p) { if (p == nullptr) { Type & r = &p; // Здесь ОС пошлет сигнал и программа аварийно завершится } else { Type & r = &p; // Здесь все должно быть хорошо } } 

Also, the pointer can be reassigned, but in the case of passing the pointer to the function it does not matter. There are a number of other cases where links and pointers serve very different purposes, but this is a reason for a separate article.

  • one
    Another & may denote ref-qualifier for member functions of a class: struct Some { void foo() &; }; struct Some { void foo() &; }; - Croessmah
  • Thank you, very helpful answer, but not quite what was needed. - raviga

The &something operator is an operator for getting the address something . Therefore, when you write &pObj , and pObj is a pointer, you pass the address of the pointer , and the function at you takes the address of some variable. The pointer dereference operator gives you access to the memory pointed to by the pointer, you can say that you are getting some kind of variable. And then, when passed to your function, its type is implicitly converted to the link.

 bar(int& u); int obj; int* pointer = &obj; bar(*pointer); // => bar(obj) bar(obj); // то, что вы хотели bar(pointer); // функция принимает аргумент типа int, а не int*. Ошибка. bar(&pointer); /* передаст адрес указателя, это подойдет, если bar принимает указатель на указатель: bar(int** u) */ bar(&obj); /* передаст адрес obj, это подойдет, если bar принимает указатель: bar(int* u) */ 
  • If the pointer without any operators ( Type* type = *ref; cout << type << endl; ) and so returns the link, then why do we need to specify the dereference operator in order to pass this link? _____ <<< And then, when passed to your function, its type is implicitly converted to a link. <<< what is the conversion to the link in the second circle, if the pointer itself already contains the link ??? - raviga

You have 2 options. Either use a pointer or a link.

 #include <iostream> void some_func(int *obj){ *obj = 6; } void some_func2(int &obj){ obj = 5; } int main(){ int obj; some_func(&obj); std::cout<<obj;//6 some_func2(obj); std::cout<<obj;//5 return 0; } 

& obj will pass a pointer to an object, not a link

 Object *object = new Object(); //Создаётся указатель на новый объект some_func(*object); //* + (указатель на тип Object) = тип Object //some_func принимает как аргумент объект, на который создаётся ссылка //именно поэтому компилятор принимает такой вариант 

    Since the function accepts a reference to an Object , you must pass an Object of type to this function.

    If you pass a pointer to an object to such a function, it is considered a type mismatch.

    If you do this:

     some_func(&pObj); 

    That, in fact, you pass the address of a pointer to an object of type Object . That is, you pass a pointer to a pointer to an object of type Object .

    The expression & pObj is of type Object **.