Originally Posted by
Elysia
No, a reference is not a memory address. It's a type that may contain data and functions. Hence it does make sense to treat it as an "int".
If you're just trying to understand references, then just think of them as aliases. They share storage with the variable they reference. In essence, they're the same variables, but with different names. You don't need to complicate it any further.
I understood that references can be used as aliases
Code:
class Foo
{
private:
int x;
public:
Foo() : x(0) {}
int getX() const {return x;}
void setX(int _x) { x = _x;}
};
int main(void)
{
Foo foo;
Foo& fooRef = foo;
printf("fooRef: %d\n", fooRef);
printf("foo: %d\n", foo);
cout << "foo.getX(): " << foo.getX() << endl;
cout << "fooRef.getX(): " << foo.getX() << endl << endl;
foo.setX(999);
cout << "After calling foo.setX(999);" << endl;
cout << "foo.getX(): " << foo.getX() << endl;
cout << "fooRef.getX(): " << foo.getX() << endl;
}
code produces following
fooRef: 0
foo: 0
foo.getX(): 0
fooRef.getX(): 0
After calling foo.setX(999);
foo.getX(): 999
fooRef.getX(): 999
But I think references might share different storage like in this case:
Code:
class Test
{
int &i; // int *const i;
int &j; // int *const j;
int &k; // int *const k;
};
int main()
{
// This will print 12 i.e. size of 3 pointers
cout<< "size of class Test = " << sizeof(class Test) <<endl;
return 0;
}