Search code examples
c++parametersconstructorpolymorphismdefault-parameters

C++ default constructors and default parameters


If I have a class containing:

foo(); //sets baz to 10
foo(int bar = 0); //sets baz to bar
int baz;

Will the 'default' constructor ever be used?

e.g. will:

foo qux;

default to baz = 0 or 10?

Any difference for:

foo * quux = new foo;

Solution

  • Will the 'default' constructor ever be used?

    No, a constructor call specifying no argument will simply be ambiguous. The compiler just cannot tell whether the constructor accepting no argument is preferable to the constructor accepting an argument with a default value, or vice versa. Your code won't compile.

    Any difference for: foo * quux = new foo;

    No, same story. Nothing changes if you are creating the object through new. The compiler will still be unable to decide which constructor you intend to call.