Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a function/method passing an argument by reference and an overload passing it by value in C++? [duplicate]

In C# this is certainly possible, as this compilable example can show:

static void Teste(int x) { }
static void Teste(ref int x) { }
static void Teste()
{
    int i = 0;
    Teste(i);
    Teste(ref i);
}


But can it be done in C++(/CLI) with a constructor? See the example below:

class Foo
{
    Foo(int bar)
    {
        // initializing "Foo" instance...
    }
    Foo(int &bar)
    {
        // initializing "Foo" instance...
    }

    //...
}

Although this class does compile with these constructors I can't see how to choose when I apply one are the other, that is, the call is ambiguos, as there is no keyword I know for this purpose as "ref" in C#. I tried it in a constructor, where the name must be the same as the class (of course I can add a useless parameter, but I want to know if I can not do it).

BTW, I googled and only got things like "what's the difference between passing by ref and by value?" but nothing covering overloading like this. And I guess that as workarounds I can use pointer, thanks to the "take the address of" (&); or have, as mentioned above, an extra useless parameter. But what I want to know is: can I have overloads like these (by ref/by value)?

Thanks in advance,

like image 444
JMCF125 Avatar asked Nov 12 '22 06:11

JMCF125


1 Answers

You can accomplish something similar in C++ by providing an explicit cast to the desired type.

struct Foo
{
    Foo(int /*bar*/) {}
    Foo(int &/*bar*/) {}
};


int main()
{
    int value = 5;
    Foo foo(static_cast<const int&>(value));

    return 0;
}

The cast to const will cause overload resolution to ignore the constructor taking a non-const reference and will settle on passing by value.

like image 119
Captain Obvlious Avatar answered Nov 15 '22 04:11

Captain Obvlious