Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

header

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?

like image 906
yasar Avatar asked Feb 13 '12 12:02

yasar


People also ask

Where the values of default arguments should be provided?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

What do you put in header vs CPP?

The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.

Do you need to include the header file or CPP?

You make the declarations in a header file, then use the #include directive in every . cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the . cpp file prior to compilation.


2 Answers

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*/) {     ... } 
like image 74
Luchian Grigore Avatar answered Sep 28 '22 02:09

Luchian Grigore


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

like image 23
Didier Trosset Avatar answered Sep 28 '22 02:09

Didier Trosset