简体   繁体   中英

How can a default constructor and a default argument constructor cause ambiguity in cpp?

Whats the difference between the default constructor and deafult argument constructor? An example will be helpful

I suppose you mean something like this:

struct foo {
    foo(int x = 1) {}
    foo() {}
};

A default constructor is one that can be called without arguments (and I suppose that is what you misunderstood). Both constructors above are default constructors. They both can be called without arguments and when you call the constructor via

foo f;

Both are viable and there is no way for the compiler to resolve the ambiguity.

A constructor where all the arguments have defaults is also a default constructor for the class.

struct Foo
{
    Foo() = default;
    Foo(int = 0){};
};

int main() {
    Foo f;
}

will not compile as there are two candidate default constructors so overload resolution will fail. (Note that Foo f(1); will compile as overload resolution is no longer ambiguous.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM