[LC++]Default Arguments

Jack Lloyd lloyd at acm.jhu.edu
Fri May 10 11:03:05 UTC 2002

What kind of things are allowed for default arguments? Specifically, can
you do something more complicated than a simple constant (for example an
expression such as "new SOME_TYPE" or "function_call()")

An example of what I'm talking about follows. I've tested this on several
compilers, and it seems to be fine, but I'd like some people's opinions.
The thing that makes me nervous is that Stroustrup never mentions doing
such things in The C++ Programming Language; all of his examples are for
simple things like "void foo(int = 0)", etc. If this is legal, what else is
or isn't? I would assume that, if "new X" is legal, one can use any
expression resulting in a type that is compatible with the argument type,
but C++ is full of odd exceptional cases.



#include <stdio.h>

class X
      const int foo;
      X(int x = 5) : foo(x) {}

class Y
      const X* x;
      void foo() { printf("%d\n", x->foo); }
      Y(X* xx = new X(42)) : x(xx) {}

int main()
   Y y1(new X(20264));
   Y y2(new X);
   Y y3;


   return 0;

More information about the tuxCPProgramming mailing list