131

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?

1
  • have you tried adding to the header? Commented Feb 13, 2012 at 12:08

4 Answers 4

182

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

2 Comments

To clarify, the declaration is the part in the header.
this is something i always confuse when setting up an empty c++ application, i really need to start using default-application setups
25

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

Comments

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).

Comments

-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 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.