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

I want to set my function with the class object parameter set by default. But when I try to do this, it does not compile.

class base {
 // ...
};

int myfunc(int a, base b = NULL) {
    if (NULL = b) {
        // DO SOMETHING
    } else {
    // DO SOMETHING
    }
}

Here, when I try to compile it, it gives me the error that "the default argument base b is of type int"

+5
source share
3 answers

You have three obvious options.

Use overloads first so that the caller can choose bor not.

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

This way you can pass bwithout using a pointer. Note that you must make a breference or pointer type to avoid slicing the object.

-, , b , NULL.

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

-, -, nullable, boost::optional.

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

NULL ++.

, :

int myfunc(int a, base b = base())
+13

@tenfour . , , :

#include <iostream>

/**
 * To build it use:
 *     g++ -std=c++11 main.cpp -o main
 */
class MyCustomClassType
{
  int var;

  friend std::ostream &operator<<( std::ostream &output, const MyCustomClassType &my_custom_class_type )
  {
    output << my_custom_class_type.var;
    return output;
  }
};

// C++11 syntax initialization call to the default constructor
MyCustomClassType _my_custom_class_type{};

void function(MyCustomClassType my_custom_class_type = _my_custom_class_type)
{
  std::cout << my_custom_class_type << std::endl;
}

int main (int argc, char *argv[])
{
  function();
}
0

All Articles