This should print 1 but this is printing 0. My thinking is x implicit reference to a so if x changes a should also change.
If I do it like this explicitly void bar(Foo& x) then it is printing 1. I wonder what is happening behind the scenes here.
My source of the learning is from Bjarne c++ 4th edition ( First 2 section done). I also did C++ in 2015-16 during the final year in college I'm familiar with the syntax.
This is extremely helpful to me as I was looking for some guidance already :)
The explanation is that your thinking is incorrect. :)
In the example x is not a reference, so a is passed by value.
The value of a is assigned to x, which is an independent variable.
So changes to x do not affect a.
There is no 'implicit reference' in C++.
When you change x to be Foo& , a is passed by reference.
This is the difference between pass by value and pass by reference, and class instances are passed by value as usual.
Yeah, I was confused initially about why to use references with the object now it makes much more sense to me. C++ is surely deep :). Thanks for your valuable comments, I will be posting my C++ endeavors as I go on learning new stuff but this time I will be precise with my word selection and topic :)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Consider the following code:
What does this output and why? :)
This should print
1
but this is printing 0. My thinking isx implicit reference to a
so if x changes a should also change.If I do it like this explicitly
void bar(Foo& x)
then it is printing 1. I wonder what is happening behind the scenes here.My source of the learning is from Bjarne c++ 4th edition ( First 2 section done). I also did C++ in 2015-16 during the final year in college I'm familiar with the syntax.
This is extremely helpful to me as I was looking for some guidance already :)
The explanation is that your thinking is incorrect. :)
In the example x is not a reference, so a is passed by value.
The value of a is assigned to x, which is an independent variable.
So changes to x do not affect a.
There is no 'implicit reference' in C++.
When you change x to be Foo& , a is passed by reference.
This is the difference between pass by value and pass by reference, and class instances are passed by value as usual.
Yeah, I was confused initially about why to use references with the object now it makes much more sense to me. C++ is surely deep :). Thanks for your valuable comments, I will be posting my C++ endeavors as I go on learning new stuff but this time I will be precise with my word selection and topic :)