Hello guys, I am trying to understand the implementation of references in C++, after some research and reading this article: An Insight to References in C++ - CodeProject
I concluded that references act simply as constant pointers (not necessarly implemented by a compiler as constant pointers).
Also what I tried to understand is a this pointer and functions that return references.
If I got it right, a this is a pointer variable that points to the address of an object and that address, so by incrementing that address we could get member fields of some object
So this logic would also apply?Code:class Foo
{
public:
int fooVar;
int fooVar2;
}
Foo fooObj; // For example let's say some Foo obj is at stack address 0x1000
fooObj.fooVar // at address 0x1000 ???
fooObj.fooVar2; // at address 0x1004 ???
Or if I have two methodsCode:// Address Of An Object 0x2000
// Since it acts as a pointer
// I can assign address to reference variable ???
Class& obj = 0x2000; // same as Class* const obj = 0x1000;
Code:Class* Class::getAddressPointer()
{
return this; // returning pointer that points to address where object address is stored???
}
Code:Class& Class::getAddress()
{
return *this; // return address where object is stored???
}
Also in this article C++ Pointers and ReferencesCode:Class objA;
Class objB = objA.getAddress(); // I don't think this is valid
there is an example:
in function squareRef, we are doing dynamical memory allocation, where address of int object is stored in a variable dynamicAllocatedResultCode:/* Test passing the result (TestPassResultNew.cpp) */
#include <iostream>
using namespace std;
int * squarePtr(int);
int & squareRef(int);
int main() {
int number = 8;
cout << number << endl; // 8
cout << squareRef(number) << endl; // 64
}
int & squareRef(int number) {
int * dynamicAllocatedResult = new int(number * number);
return *dynamicAllocatedResult;
}
so writing
*dynamicAllocatedResult will dereference pointer and get an integer value,
but what confuses me that function returns integer reference.
This line returns an integer value of 64
And havingCode:return *dynamicAllocatedResult;
equals to theCode:int & squareRef(int number)
???Code:int* const squareRef(int number)
So if a function actually returns const pointer, why are we returning an integer value and not pointer which points to that integer value?
Is it because compiler does work for us so basically having this line:
is actually same as this one:Code:return *dynamicAllocatedResult;
Thank you in advance!Code:return &dynamicAllocatedResult;