Referencing a function

Hello.

Can someone help me understand this.

If i have a fnction like this

1
2
3
4
string& Basic_Functions::printval(std::string &str){
    
    return str;
}


and I call it

1
2
3
4
5
    string  sample = "This is a sample";
    cout << sample<< endl;
    
    string i1 = printval(sample) = "haha"; 
    cout<< i1 <<endl;



What does the function printval refer to? Because it should be a reference should be bound to something. Im not really sure what does that function refer to. Thanks
The function returns a reference to 'str', which in turn is a reference to 'sample' (during this call of the function).

Thus, line 4 seems effectively the same as string i1 = sample = "haha";

SO does it make a difference if i just do this

1
2
3
4
string Basic_Functions::printval(std::string &str){
    
    return str;
}


I remove the reference and just declare an ordinary function with a reference as parameter

Because they return the same output. and since i am returning the str to the function w/c is reference to the sample variable making the function a reference doesnt make any sense to me.

IF its not so much to ask can you give me an example that shows the difference of using a reference function?
Last edited on
std::string& foo( std::string& str ) { return str ; }
returns an lvalue - it returns an expression that identifies a non-temporary object.
Reference to the non-temporary object str is returned.

std::string bar( std::string& str ) { return str ; }
returns a prvalue (pure rvalue) - it returns an expression that identifies an anonymous temporary object.
Conceptually, an anonymous copy of str is made and that temporary object is returned by value.

> example that shows the difference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>

std::string& foo( std::string& str ) { return str ; }

std::string bar( std::string& str ) { return str ; }

int main()
{
    std::string s ;
    
    std::string& fine = foo(s) ; // fine, reference to non-temporary object
    
    const std::string& also_fine = foo(s) ; // fine, reference to const extends the life of the temporary object

    std::string& not_fine = bar(s) ; // *** error *** reference to non-const can't bind to a temporary object 
}

http://coliru.stacked-crooked.com/a/cd3e4905d65c75bd
I see..

Thanks for the explanation and the example

Topic archived. No new replies allowed.