pass by reference

T

thomas

hi guys, I got a question about "pass by reference".

I want to know if I can pass a reference handler of a stack object to
a function as parameter?
----code---
void func(classtype &x);
classtype x;
func(x);
-----code---

Will this work? seems that the "x" object is in stack
Can "func" know where to find the "x" object?
 
T

thomas

Remove the words "a reference hanlder", replace "stack" with "local",
and you have a better (closer to idiomatic language) statement; and
the answer is "yes, you can".


I do sincerely hope you mean the previous statements are inside some
function in your program.



What do you mean by "where to find"?  Your function has a reference
to the object.  It uses the reference to "find" the object, so to
speak, just like if you would declare the reference to you 'x' in
the same scope as 'x' itself.  The reference becomes the object's
alias, a way for the function to get to the object, its members, and
even its location if you so desire (taking the address of a reference
yields the address of the object).  You can verify that you get the
same object by printing the address inside the function and outside:

    #include <iostream>
    #include <ostream>

    class classtype {};

    void foo(classtype& r) {
        std::cout << "inside: " << &r << std::endl;
    }

    int main() {
        classtype x;
        std::cout << "outside: " << &x << std::endl;
        foo(x);
    }

V

I accept your advice and thank you for your efforts.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top