const Reference

Oct 22, 2014 at 2:05pm
Can you explain what is done when we call fuction void Foo(const int& x)

//main.cpp

1
2
3
4
5
6
7
8
void main()
{
....
int a = 6;
Foo(a);

...
}


Thanks in advance!!
Oct 22, 2014 at 2:17pm
that's fairly pointless for primative types, but when passing large objects into a method then passing by ref means you aren't passing the actual object, you're just telling the function where the object is. and making it const means your compiler will guarantee it wont be changed.

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Oct 22, 2014 at 6:02pm
4: int "a" allocated at stack and filled with 6.
5: address of int "a" (pointer to variable "a", allocated at stack) pushed into stack.
Then Foo() called.
When Foo() started, it reads pointer to variable "a" from stack and uses it as pointer to "x".
So when you read "x", you actually read "a".
Moreover, you can't chage x cause it's marked as const.
If You switch on optimization, compiler can make something else (I dunno what).
Oct 23, 2014 at 5:30am
So, a wont change
Topic archived. No new replies allowed.