120

I am kind of new to C++. I am having trouble setting up my headers. This is from functions.h

extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect *);

And this is the function definition from functions.cpp

void
apply_surface(int x, int y, SDL_Surface * source, SDL_Surface *
destination,SDL_Rect *clip = NULL)
{
    ...
}

And this is how I use it in main.cpp

#include "functions.h"
int
main (int argc, char * argv[])
{
    apply_surface(bla,bla,bla,bla); // 4 arguments, since last one is optional.
}

But, this doesn't compile, because, main.cpp doesn't know last parameter is optional. How can I make this work?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
yasar
  • 13,158
  • 28
  • 95
  • 160

4 Answers4

171

You make the declaration (i.e. in the header file - functions.h) contain the optional parameter, not the definition (functions.cpp).

//functions.h
extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect * clip = NULL);

//functions.cpp
void apply_surface(int x, int y, SDL_Surface * source, SDL_Surface *
destination,SDL_Rect *clip /*= NULL*/)
{
    ...
}
rayryeng
  • 102,964
  • 22
  • 184
  • 193
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
23

The default parameter value should be in the function declaration (functions.h), rather than in the function definition (function.cpp).

Didier Trosset
  • 36,376
  • 13
  • 83
  • 122
3

Use:

extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect * = NULL);

(note I can't check it here; don't have a compiler nearby).

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
-4

Strangely enough, it works fine for me if I have a virtual function without a default parameter, and then inheritors in .h files without default parameters, and then in their .cpp files I have the default parameters. Like this:

// in .h
class Base {virtual void func(int param){}};
class Inheritor : public Base {void func(int param);};
// in .cpp
void Inheritor::func(int param = 0){}

Pardon the shoddy formatting

  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31138284) – BobMorane Feb 26 '22 at 16:04