(1) Why can't this be compiled when count is a regular variable and not a reference type?
This is a very interesting question. The question should rather be why the code compiles when count declared as a link. :)
A regular variable error, because int count not modified inside the const qualified function operator()(int &i) const; .
The links are a bit different. In your code, you declare the method as const , which means that count relating to i can no longer refer to anything else.
But this is still impossible due to the nature of the links :). After initialization, you cannot change the binding binding.
operator() just checks if you are changing the count binding to something else or not? And the answer is always no. Since count++ changes the value indicated by count , not the binding.
It doesn't matter in your code whether the member method is const or not when it comes to int& count .
Take int& count; to int* const p_count; and try to simulate the situation yourself.
(2) Why can't this be compiled? Am I changing ctor to the following?
CountFrom(int &n) { count = n; }
Because the link must be assigned to a variable during initialization. In a simple example
int i, &r; // error, because 'r' not initialized r = i; // this is not initialization but a copy
On the side of the note, you should be especially careful when dealing with reference variables inside a class . Because it is easy to damage their scale and reality.
For example, here the validity of count depends on area i .
Change After the 2nd edit, it’s very trivial to find out why this version works.
Because count now a simple variable. It can be skipped from initialization in the constructor initializer list, as opposed to a link.
In addition, the correctness of const operator() missing, so now you can change any class member variable inside.
You must select the version of the const member method if you want to indicate that the class element should "change" inside it (unless some variable is mutable or you use const_cast ). In all other cases, use the regular version of the member method. They can both coexist, as well, depending on your business logic. This is a slightly broad question, and for this it is worth having another stream.