Search code examples
c++default-valuefunction-parameter

Default Parameters in Functions - C++


If I'm not wrong this kind of declaration may be used to assign default values in a constructor:

/* .h */
class FooClass(){

   private:
     int* data;
     int depth, rows, columns;
     char* desc;

   public: 
     ... 
}

/* .cpp */
FooClass::FooClass()
    : data(NULL), depth(0), rows(0), columns(0), desc(NULL)
{
     //whatever constructor does...
}

but it is not admitted to assign default values to parameters in a function:

NOT OK

/* .h */
class FooClass(){

   public:
      void foofunc(int var1, int var2, int var3, int var4);
}

/* .cpp */
FooClass::foofunc(int var1, int var2)
    : var3(0), var4(5)
{
     //whatever function does...
}

which must instead be done like this:

OK

/* .h */
class FooClass(){

   public:
      void foofunc(int var1, int var2, int var3 = 0, int var4 = 5);
}

/* .cpp */
FooClass::foofunc(int var1, int var2, int var3, int var4)
{
     //whatever function does...
}

Why?


Solution

  • The first example isn't one of "default values" at all - that is an initialisation list for the members and bases of the object, which only makes sense in a constructor. Constructors can however have default argument values, using the same syntax as for any other function.

    So this is fine, for example:

    explicit FooClass(int* data = NULL, int depth = 0, int rows = 0, int columns = 0, char* desc = NULL)
        : data(data), depth(depth), rows(rows), columns(columns), desc(desc)
    {
    }
    

    If you need more than just simple default values for any kind of function, consider overloading the function, e.g.:

    void my_function(int a, int b)
    {
        // do stuff with a and b
    }
    
    void my_function()
    {
        // version with no arguments, "default" behaviour
    }