I'm new to C++ and I'm confused about the differences between a normal ordinary reference to a read-only reference. The following two points are from http://www.lmpt.univ-tours.fr/~volkov/C++.pdf.
A reference must be initialized when it is declared, and cannot be modified subsequently. In other words, you cannot use the reference to address a different variable at a later stage.
A reference that addresses a constant object must be a constant itself, that is, it must be defined using the const keyword to avoid modifying the object by reference.
I was wondering, how to understand it? A normal reference is different to a read-only (or constant) reference; because a read-only reference can point to a constant object, in contrast to a normal reference. But the above two points are really confusing...Especially, "a reference must be initialized when it is declared, and cannot be modified later".
EDIT: sorry that I did not make it clear earlier. What I intended to ask is that, what is the difference between a normal reference and a read-only reference? It has nothing to do with pointers for now.
EDIT again: I finally figure it out. For completeness, the following is the code and comments.
#include <iostream>
#include <string>
using namespace std;
int main(){
string line(50, '-');
/* a constant reference, non-constant object */
int i=42; // a non-constant object
const int& r1 =i; // a constant reference r1, which reference the earlier defined variable i
//r1 = 6*9; // Error: tried to change the reference r1
i = 50;
cout << "r1: " << r1 << endl;
cout << "i: " << i << endl;
/* a constant reference, constant object */
const int j = 40;
// int& r2 = j; // Error, because j is a constant, it requires a constant reference
const int& r2 = j;
// j = 45; // Error, because j is a constant
//r2 = 20; // Error, because r2 is a constant reference
/* non constant reference, non constant object */
int k = 30;
int& r3 = k;
r3 = 10; // update
cout << "r3: " << r3 << endl;
cout << "k: " << k << endl;
cout << line << endl;
k = 40; // update
cout << "r3: " << r3 << endl;
cout << "k: " << k << endl;
return 0;
}
EDIT again again: Now, I'm confused with "a reference must be initialized when it is defined, and cannot be modified later".
/* how to understand a reference can not be used to address a different variable */
int a = 1;
int b = 2;
int& r = a; // r is a reference, which references variable (object) a
r = b; // expect an error, but did not get an error
cout<< "a: " << a << endl; //2
cout<< "b: " << a << endl; //2
cout<< "r: " << a << endl; //2