2

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

2 Answers2

5

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • @YatharthKumar by having only a single default constructor. Having more than one is uncommon – 463035818_is_not_an_ai Oct 06 '20 at 13:51
  • @YatharthKumar yes, you can keep both, you can call the first when you provide an argument to it, but you cannot call either of them without argument, because they are ambiguous. If you have problem with some code, I can only help you after seeing the code. Maybe you want to open a new question to ask about your actual problem. Please do not change this question to ask for something else, because the current answers answer the question as is – 463035818_is_not_an_ai Oct 06 '20 at 14:27
2

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.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483