-1

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;
Flexo1515
  • 1,007
  • 1
  • 10
  • 27
  • 3
    Note: these are *both* default constructors. – Oliver Charlesworth Mar 11 '13 at 00:18
  • 1
    Seems like a reasonable question, why do people always downvote things just on the basis of them being simple? From the FAQ - *"Be tolerant of others who may not know everything you know."*. Further, this isn't the sort of thing you'll typically find in an introductory C++ book. – JBentley Mar 11 '13 at 01:49

2 Answers2

6

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.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
1

This is an ambiguous call. As such, I don't think it should even compile. The compiler can't decide whether you meant to call the foo::foo(int) constructor or the default constructor, foo::foo().

Tushar
  • 8,019
  • 31
  • 38