-1

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
}
3
  • Side note : If it has been that long since you used C++, read this C++ core guidelines a lot has changed since then so it might be good for you to pickup a bit of the latest idioms :) As for your problem that's mostly a typo, the default parameters are in the wrong place Commented Oct 18, 2024 at 20:16
  • 1
    remove the defaults from the definition, they should only be in the declaration, otherwise the compiler will fail to compile the definition and you will get an unresolved symbol error Commented Oct 18, 2024 at 20:19
  • The syntax errors in your code indicate that it was not copy-pasted. When I fixed them, your code compiled. Details matter. Copy-paste code; don't try to type it in the question. Commented Oct 18, 2024 at 20:23

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Also thanks for catching the typos, I'll update the code to keep it right for future views

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.