5

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,

JBentley
  • 6,099
  • 5
  • 37
  • 72
JMCF125
  • 378
  • 3
  • 18
  • Try initialising the constructors by passing a pointer to one and a value to the other and see what you get – smac89 Apr 21 '13 at 21:14
  • This may be a duplicate, but in my defence, I don't search very well; besides, the name of the other question isn't very catchy (although the name of this one is even less). Also, as a sidenote, the other guy asks if it is makes sense, I ask if it is possible. – JMCF125 Apr 22 '13 at 15:46

1 Answers1

1

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.

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74