Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload resolution of constructors for different classes

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?

like image 775
Karen Melikyan Avatar asked Jun 10 '19 07:06

Karen Melikyan


People also ask

Can you overload the constructor of the class?

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.

What is overload resolution?

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.

Can you overload the constructor of the class Java?

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.

What are the various constructors explain constructor overloading in detail?

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.


1 Answers

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.

like image 199
StoryTeller - Unslander Monica Avatar answered Oct 20 '22 22:10

StoryTeller - Unslander Monica