Search code examples
c++default-parameters

Using default values in C++ Function declaration


It's been quite a while (18+ years) since I've been coding in C++.

I am running into a problem with using default parameters in a function, then trying to call that function with only the non defaulted parameter. As an example here is my class declaration

//foo.h
#pragma once
struct foo
{
  void bar(int, int, int);
  void snafu();
}

I then try to call foo::bar(3) from within the foo::snafu() function.

//foo.cpp
#include "foo.h"
void foo::bar(int x, int y = 1, int z =2)
{
... do stuff
}

void foo::snafu()
{
  foo::bar(5) //Error C22660 Function does not take 1 argument
}

Solution

  • You need to put the default values in the declaration of the method, not in the definition.

    foo.h

    #pragma once
    
    struct foo
    {
      void bar(int x, int y = 1, int z = 2);
      ...
    }
    

    foo.cpp

    #include "foo.h"
    
    void foo::bar(int x, int y, int z)
    {
        ... do stuff
    }
    
    ...
    

    Also, you have 2 typos in your foo:snafu() definition. You are using : instead of ::, and you don't need to refer to bar() as foo::bar() inside of snafu().

    void foo::snafu()
    {
        bar(5);
    }