Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an int& parameter with a default value?

Tags:

c++

I have to add a default int& argument (Eg iNewArgument) to an existing function definition in a header file:

What is the syntax to initialize the last argument to make it take a default value?

..
virtual int ExecNew
    (int& param1, int& RowIn,int& RowOut, char* Msg = '0', 
            bool bDebug=true, int& iNewArgument = NULL ) = 0 ;
.
.

NULL is #defined to 0

Error: default argument: cannot convert from int to int&

like image 653
user85917 Avatar asked Jan 20 '26 14:01

user85917


2 Answers

Your example indicates that you are creating a virtual function. Default arguments in virtual (especially pure) functions are not a good idea, because they are not considered when you call an overridden function.

struct A {
  virtual void f(int = 4711) = 0;
};

struct B : A {
  virtual void f(int) { /* ... */ }
};

Now, if someone calls f on a B object, he will have to provide the argument - the default isn't used. You would have to duplicate the default argument in the derived class, which creates ugly redundancies. Instead, you can use the non-virtual interface pattern

struct A {
  void f(int a) {
    int out;
    f(a, out);
  }

  void f(int a, int &out) {
    doF(a, out);
  }

protected:
  virtual void doF(int a, int out&) = 0;
};

The user can now call f with one, and with two arguments, from whatever class type he calls the function, and the implementers of A don't have to worry about the default argument. By using overloading instead of default arguments, you don't need to break your head around lvalues or temporaries.

like image 91
Johannes Schaub - litb Avatar answered Jan 22 '26 05:01

Johannes Schaub - litb


The only meaningful way to supply a default argument to a non-const reference is to declare a standalone object with static storage duration and use it as a default argument

int dummy = 0;

...
virtual int ExecNew(/* whatever */, int& iNewArgument = dummy) = 0;

Whether it will work for you or not is for you to decide.

Inside the function, if you'll need to detect whether the default argument was used, you may use address comparison

if (&iNewArgument == &dummy)
  /* Default argument was used */
like image 36
AnT Avatar answered Jan 22 '26 05:01

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!