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.

Where Am I?

You are currently browsing the C++ category at JAWS.

Follow

Get every new post delivered to your Inbox.

Join 1,036 other followers