Consider this code.
struct A {
int i;
};
struct B {
char c;
};
struct C {
double d;
};
void f(A a);
void f(B b);
void f(C c);
void g()
{
f({5});
}
Here I get an ambiguity in f({5});
. But it seems that struct A
's constructor is an exact match for {5}
, while the second one needs an integral promotion, while the last one needs a floating-point conversion.
So why is there an ambiguity?
Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments.
The process of selecting the most appropriate overloaded function or operator is called overload resolution. Suppose that f is an overloaded function name. When you call the overloaded function f() , the compiler creates a set of candidate functions.
Yes! Java supports constructor overloading. In constructor loading, we create multiple constructors with the same name but with different parameters types or with different no of parameters.
The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task. Consider the following Java program, in which we have used different constructors in the class.
Even if the first conversion in the sequence is of a worse rank, both conversion sequences end up being user defined conversions, since they both convert to a user defined type.
[over.ics.user]
1 A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion ([class.conv]) followed by a second standard conversion sequence.
A user defined conversion anywhere in the implicit conversion sequence gives the entire sequence a "user defined conversion" rank. So the two conversion sequences are in fact of the same rank, and as such neither is better than the other.
The function call is ambiguous on account of that.
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