By returning an object reference, the const specifier will not allow the object to be modified:

const int& foo() { ... } int main () { foo=5; //error: assignment of read-only location 'f()' return 0; } 

But how will const int foo () differ from int foo ()? We are talking about functions NOT class members.

And do I understand correctly that the function that returns the link can be used as an lvalue ?:

 int& foo() { ... } int bar() { ... } int main () { foo=5; //OK bar=5; //error return 0; } 
  • Are the brackets lost in main? - dzhioev
  • In the question Но чем будет отличаться const int foo() ? Did you mean const int & foo() ? - Cerbo
  • @Cerbo No, I wrote everything correctly. What difference does the function return const int or int, if the returned value can not be changed anyway - this is the essence of my question. - aryndin

1 answer 1

But how will const int foo () differ from int foo ()?

const int foo() int foo() hardly differs from int foo() . Differences can manifest themselves only in particularly tricky cases of resolving overloading functions - but these cases are of no interest to anyone.

We are talking about functions NOT class members.

Even if functions are members of classes (i.e. methods ), they are all the same no different.

And do I understand correctly that the function that returns a link can be used as an lvalue?

The value of the function that returns the reference can be used as an lvalue :

 int& foo() { ... } int bar() { ... } int main () { foo()=5; //OK bar()=5; //error return 0; }