Using (return val of) member function as default parameter of member function
11 November, 2009 § 2 Comments
C++ allows the programmer to do some really cool things. When writing code I try to follow the Google C++ Style Guide, so I haven’t gotten much experience with the fringe areas of default parameters. A question was recently asked on the comp.lang.c++.moderated usenet group where the OP wanted to place a member function as the default argument, a la:
class foo { int getInteger(); void doSomething(int i = getInteger()) { } };
Many of the responses said that he should overload doSomething
as a nullary function and call the original doSomething
with the return value of the member function. Within most of these comments was one from Neil Butterworth, who mentioned that the reason this isn’t possible is because the this
pointer is not available until the body of the function. He offered that the OP could make getInteger
a static function.
class foo { static int getInteger(); void doSomething(int i = getInteger()) { } };
And if you don’t believe him, you can use the Comeau C/C++ Online Compiler to see for yourselves.
I thought this was really cool. While I may not have a use for it at the moment, it is questions like these that are great conversation starters. About a month ago I subscribed to the clcm mailing list and I now recommend it to others as a way to learn different uses of C++ and interesting conversations about the language.
Hey Jared,
Too bad you cannot do this:
int NumberPlusOne(int nInput) { return nInput + 1; }
void SomeFunction(int nNumber1, int nNumber2 = NumberPlusOne(nNumber1) )//Look at this line
{
}
int main()
{
SomeFunction(2);
return 0;
}
If you could there could be a way to use non-static member functions; but you’d have to pass the address of the object (keyword ‘this’ when inside the body of the object). Oh well; it didn’t work.
I wonder if you can get something like that to work using templates…
Or to ruin the party you could just add an overload to the function that calls SomeFunction with the result of NumberPlusOne inside of the body, but then it’s no fun 🙂