like this code
int i = 42;
int *p = &i;
int *&r = p;
*r = 0;
The r
is reference and is not a object, so why it can be used with *
.
CodePudding user response:
why reference is not a object
Because the that's how references are specified in the language.
The "r" is reference and is not a object,so why is can be used with "*".
Because the object that r
refers to is a pointer, and you can use a pointer as an operand to the unary *
operator.
CodePudding user response:
A reference can be bound to things other than objects. Remember that a pointer is also an object. So a reference can be bound to a pointer too, or to even another reference. See for yourself with some throwaway code:
#include <iostream>
template<class T>
struct Foo
{
Foo(T& t){
std::cout << t << "\n";
}
};
int main() {
int object = 1;
int* pointer = &object;
int& reference = object;
int*& reference_to_pointer = pointer;
Foo<int> o1(object); // passing 'object' by reference
Foo<int*> o2(pointer); // passing a pointer to 'object' by reference
Foo<int&> o3(reference); // passing the reference to 'object' by reference
Foo<int*&> o4(reference_to_pointer); // passing a reference to a pointer to 'object' by reference
}