Search code examples
c++return-by-reference

C++ Returning a Reference of an Object


I'm currently in a C++ Course and im struggling with References. I know there are some similar topics, but i couldnt find an answer for this. The thing is my Prof wants us to use References when returning objects, so return by value or using a pointer as return is no option. So i guess i have to use a dynamic allocated object (returning a reference to a local object ends in a mess...right?)

1. Complex& method() {
2. Complex *object = new Complex();
3. return *object; }

Here is where im struggling, how do i catch the return right?

1. Complex one = object.method();

As far as i understand, with this i will get only a Copy and a Memory Leak So how do i catch it with a pointer?

1. Complex *two = new Complex();
2. delete two;
3. *two = object.method(); 

this seems to work, but is there a way of it in just one line? Or should it be done different?


Solution

  • my Prof wants us to use References when returning objects

    When I read this, my first thought was that your professor meant:

    void method(Complex& nonConstPassByReference) 
    {
        nonConstPassByReference.data = 10;
    }
    

    or

    int method(Complex& nonConstPassByReference) 
    {
        nonConstPassByReference.data = 10;
        return (0);  // no error occurred
    }
    

    And when I use this technique, I now use

    std::string method(Complex& nonConstPassByReference) 
    {
        std::stringstream ss;
        nonConstPassByReference.data = 10;
        // more stuff
        if (anErrorOccurred) 
           ss << errorDescriptionInfo << std::endl;
        return (ss.str());  // no error occurred when return size is 0
    }
    

    This comes from the idea that, in general, all methods or functions can have two kinds of formal parameters. We call them pass-by-value, and pass-by-reference.

    In general, all functions / methods can have both input and output formal parameters. And usually, input parameters are pass-by-value. Output parameters are non-const-pass-by-reference, inviting the method body to send its results back to the prebuilt instance of the calling code.

    Occasionally, pass-by-reference variables are used for 'input-to-method' parameters (perhaps for performance - to avoid an expensive copy). In this case, the input-to-method-pass-by-reference parameters should be marked with 'const', to ask the compiler to generate an error if the code tries to modify that input.

    Note that many C functions do NOT return a value which is part of the action ... return is instead an 'error occurred' indication, with the error description stashed in errno.