Should C++ function default argument values be specified in headers or .cpp source files?

yasar picture yasar · Feb 13, 2012 · Viewed 45.9k times · Source

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?

Answer

Luchian Grigore picture Luchian Grigore · Feb 13, 2012

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*/)
{
    ...
}