How to implement C# out parameters in C++?

C++ lacks the syntactic sugar of C# and leaves the developer with several options to implement out parameters. Either declare the function parameter as a double pointer (which passes the pointer by value) or as a reference to a pointer (which passes the pointer by reference). The former case looks as follows:

void createRect(Rect **r)
{
    *r = new Rect(1, 2);
}

int main(int argc, char **argv)
{
    Rect *p;
    createRect(&p);
    return 0;
}

In this case we pass the Rect pointer by value and this is why we need to have a double pointer in the function declaration. Note that if there is a single pointer in the function declaration, the changes of r will remain only in the scope of the createRect function.

The second option looks as follows:

void createRect(Rect *&r)
{
    r = new Rect(1, 2);
}

int main(int argc, char **argv)
{
    Rect *r;
    createRect(r);
    return 0;
}

Note that in this case the pointer is passed by reference and the function works directly with the pointer instead with its copy. Also, the changes made in the createRect function are visible to the caller.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.