How to set default parameter as class object in c++?

c++

Solution

You have three obvious options here.

First, use overloads so the caller can choose to pass `b` or not.

int myfunc(int a) { ... }
int myfunc(int a, base& b) { ... }

This way you can pass `b` without having to use a pointer. Note that you should make `b` a reference or pointer type to avoid slicing the object.

Secondly, if you don't want 2 separate implementations, make `b` a pointer, which can be set to `NULL`.

int myfunc(int a, base* b = NULL) { ... }

Third, you could use something to encapsulate the concept of nullable, such as `boost::optional`.

int myfunc(int a, boost::optional<base&> b = boost::optional<base&>()) { ... }

Problem

I want to set my function with class object parameter set as default. But when I try to do that it fails in compilation. ``` class base { // ... }; int myfunc(int a, base b = NULL) { if (NULL = b) { // DO SOMETHING } else { // DO SOMETHING } } ``` Here when i am trying to compile it, this gives me error that "Default Argument base b have int type"

Original source