Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!samsung!brutus.cs.uiuc.edu!apple!voder!procase!roger From: roger@procase.UUCP (Roger H. Scott) Newsgroups: comp.lang.c++ Subject: Re: functions as default parameters Message-ID: <93@pascal.procase.UUCP> Date: 2 Mar 90 02:59:45 GMT References: <4800087@m.cs.uiuc.edu> Reply-To: roger@procase.UUCP (Roger H. Scott) Organization: proCASE Corporation, Santa Clara, CA Lines: 42 In article <4800087@m.cs.uiuc.edu> nelson@m.cs.uiuc.edu writes: > >Well, today I discovered that default parameters can be a function, that > is to say that the following is legal: > class Fred { > public: > void bill (int b = printf ("default")) {}; > } Not to be overly pedantic, but default *arguments* [not "parameters"] are *expressions*, which can contain function *calls* [not "functions"]. There are cases where it would be interesting to allow *functions* as either arguments or argument initialiers: class Wilma { public: void bambam(void (*)() = (){printf("some function\n");}); ... } ... Wilma betty; betty.bambam(() {printf("some other function\n");}); but (obviously) neither of these is legal in any current C++. > >Now what I would _like_ to do is: > class Jim { > public: > void printData (char *data, int length = strlen (data)) {}; > } >(That is to say that we can assume that if length is not supplied, then the > passed data is actually a string.) > >But it gets upset since "data" is not yet defined/in that scope. Is there > a way to get around this??? A common "trick" in this case is to pick a default value that is not within the range of reasonable (or legal) "user supplied" values. You can then test for this value inside the function and replace it with whatever computed value you want.