"josh" <xd********@yahoo.comwrote in message
news:11**********************@e3g2000cwe.googlegro ups.com...
Hi, how really work behind the scene the pass-by-reference in C++?
I know that in C++ like the C the objects are passed by-values and if
we want
we can simulate the pass-by-reference using the pointers...
Bye
I'm not quite sure what your quesiton is, is it how do we work with passing
by reference, or how does the compiler do it itself?
How we do it is quite simple:
void MyFunc( std::string& MyString )
{
std::cout << "Length " << MyString.length() << std::endl;
MyString = "";
}
int main()
{
std::string SomeString = "Hello";
MyFunc( SomeString );
}
In a function/method that accepts a reference you can use the variable as if
it was declared on the local scope, yet it effects the passed in varaible.
That is, in this example, SomeString is actually being cleared because the
reference to it is being cleared in the function.
How does it work behind the scenes? As I understand it, the compiler
actually just passes some type of pointer (some just a pointer, some maybe
more), and the compiler treats it as a reference instead of a pointer, I.E.
I used .length() and not ->length().
There are more complexities of variables being delared as references, such
as they have to be initialized (seated) and you can not reseat a reference.
In this case they just become aliases for a variable.
int main()
{
int MyInt = 10;
int& MyIntRef = MyInt;
// Above line makes MyIntRef point to MyInt
MyIntRef = 20;
// MyInt is now 20
}
Does that help?