[LC++]Default Arguments

Shaul Karl shaulka at bezeqint.net
Sat May 11 00:54:06 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.
> 
> Thanks,
>   Jack
> 
> Example:
> 
> #include <stdio.h>
> 
> class X
>    {
>    public:
>       const int foo;
>       X(int x = 5) : foo(x) {}
>    };
> 
> class Y
>    {
>    public:
>       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;
> 
>    y1.foo();
>    y2.foo();
>    y3.foo();
> 
>    return 0;
>    }
> 


According to the `C++ Primer', 3rd edition, page 353:

      A default argument does not have to be a constant expression. Any 
    expression can be used.

    [skipping an example] 

      When the default argument is an expression, the expression is 
evaluated
    at the time the function is called



-- 

    Shaul Karl
    email: shaulka(replace with the at - @ - character)bezeqint.net 






More information about the tuxCPProgramming mailing list