Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using one of the parameter's getter to set the value of another parameter in a C++ function?

In a C++ function, can I use one of the parameter's getter to set the default value of the other parameter following it? For example if I have the followig class Foo,

class Foo{
   public:
      setID();
      getID();
   private:
      string id;
}

Can I write a function fooManipulator like this,

int fooManipulator(Foo bar, string id = bar.getId());
like image 339
DJM Avatar asked Dec 05 '25 01:12

DJM


2 Answers

No, as has been stated, the order of evaluation of arguments to a function is unspecified.

However, you can achieve the effect easily with an overload like this:

int fooManipulator(Foo bar)
{
    return fooManipulator(bar, bar.getId());
}
like image 139
Benjamin Lindley Avatar answered Dec 07 '25 17:12

Benjamin Lindley


No. You cannot refer to another parameter in a default argument because the order of evaluation of function arguments is unspecified.

For example, in your fooManipulator function, the argument passed to parameter id may be evaluated before the argument passed to parameter bar. This could make invalid the use of bar in the default argument for parameter id.

like image 35
James McNellis Avatar answered Dec 07 '25 17:12

James McNellis