Default Value to a Parameter While Passing by Reference in C++

Is using a reference parameter with default value good practice?

It's not a horrible practice, but it's generally better to provide overloads:

void f(std::string const& s) { std::cout << "\\" << s << "\\\n"; }

void f() { f(""); }

It avoids some language features that end up being confusing to many people. For example, what does this print?

struct base { virtual void f(int i = 42) { std::cout << i; } };

struct derived : base { void f(int i = 19) { std::cout << i; }};

int main() { base * b = new derived(); b->f(); }

There are also ambiguity errors that can come up when you're using default parameters that don't when you use overloads.

As far as const references in particular, that doesn't really matter much. The default value binds to reference for the lifetime of the function call. It has no effect at all really. You might get better results using values sometimes when the compiler can perform certain optimizations that are not possible with reference parameters, but generally it's not something to be concerned with.

Of course, this doesn't work with non-const references because they don't bind to temporaries.

Passing optional parameter by reference in c++

The default argument of a (mutable) reference must be an l-value. The best I can think of, without overloading, is

static double _dummy_foobar;
void foo(double &bar, double &foobar = _dummy_foobar)

C++ pass a non const string by reference with default value

You can get the equivalent behavior that you are describing by using a separate overload instead of a default value:

class ClassName {
public:
ExceptionClass someFunc(int a, float b, map<int, string> c, string &d);
ExceptionClass someFunc(int a, float b, map<int, string> c) {
string d = "";
return someFunc(a, b, c, d);
}
};

C++ pass pointer by reference and assign default value

The error message says it all: you are passing an integer instead of a reference-to-a-pointer-to-SomeType. To do what you want, you can use a pointer-to-a-pointer-to-SomeType:

void myFunc(SomeType** var=NULL);

void MyClass::myFunc(SomeType** var){
if(var!=NULL && *var!=NULL)
(**var)=(*someOtherPointer);

if(var!=NULL && someCondition)
*var=NULL;
}


Related Topics



Leave a reply



Submit