Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading