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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With