user3027198
user3027198

Reputation: 303

Will default constructor still be created if I explicitly define a constructor with arguments?

Will default constructor still be created if I explicitly define a constructor with arguments but no default constructor?

Thank you!

Upvotes: 4

Views: 752

Answers (3)

Jean-François Fabre
Jean-François Fabre

Reputation: 140178

No, it won't, that's the point when you want class users to explicitly provide arguments.

However, if you use default values for your parameters, it becomes the default constructor

class Foo
{
     Foo(bool flag=false);  // not a default constructor, but acts the same
};

Upvotes: 4

Javi
Javi

Reputation: 36

No. If you define a constructor, only the constructors that you define are present. If you want to keep the default constructor, you have to redefine it.

class MyClass
{
   MyClass(){};
.
.
.
};

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

No, you have to explicitly provide the default constructor in that case.

Although you can (from C++11 onwards), for a class Foo, use the syntax

Foo() = default;

within the class declaration which reintroduces the compiler-generated default constructor. (Note you need to put this in the public section for exact equivalence).

Alternatively, if you provide default arguments to all the constructor parameters, then it becomes the default constructor.

Upvotes: 8

Related Questions