Hi guys, I'm a novice C++ programming taking my second term of programming in university. My teacher claims that pointers and references are equivalent. For example:
int & a = c;
int * b = &c;
would be said to be both pointers to c.
I've also been told that functions that return or pass by reference are said to be passing/returning pointers. But from my experience (which is limited) I don't understand how this is the case.
For example, in this function which passes by reference:
void f(int & a)
it's my understanding that a is essentially an alias for the whatever argument is used in the call (I.E. it is the argument). But if a reference is a pointer, why do operations like *a not work? Similarly, why can the function f() not even be called using pointers? For example, if I defined a pointer int * b and then try to invoke f() without dereferencing b first using the call f(b), it results in a compilation error.
Another situation that seems to contradict the fact that a pointer is a reference is the following overload of the assignment operator:
Base & operator=(const Base & right){
// body ...
return *this;
}
The function is return by reference, which my teacher would claim to be returning a pointer. However "*this" is returned (the dereference which is the object itself). If a pointer was being returned then wouldn't the return be "this" (without the *)? If these 2 are the same why are they not interchangeable in terms of passing, returning and assigning?
I understand that passing and returning by reference essentially works by passing/returning the address of the variable and a pointer does hold an address, so they're similar in this sense but I fail to see how they are identical if they cannot be used interchangeably.
So are pointers and references the same thing? Any clarification you guys could give would be great. Thanks.
References are NOT pointers, they're aliases for other objects like you said. Nevertheless, they behave similar to (self-dereferencing) pointers and are generally implemented using pointers on the assembly level.
Well I guess this is kind of worrisome considering that I'm going to be tested on these concepts and my teacher seems convinced that references and pointers are identical. In the second midterm we were asked if the following function:
template<typename T>
void swap(T & a, T & b){
T temp = a;
a = b;
b = temp;
}
swaps two values by using pointers. I put false believing that a function that is pass by reference does not correspond directly to using pointers. Needless to say I received 0 on the question.
At this point I really just want to understand, and quite frankly I wish my teacher was right as opposed to my own contracting experiences or what other sources are saying online because it creates a huge dilemma for future test/assessments when I have 2 contradicting sources of information.