How to set default parameter as class object in c++?
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&>()) { ... }
Objects can't be NULL
in C++.
To set the parameter to default, just use:
int myfunc(int a, base b = base())