-1

I have a function which needs default parameter:

LINE 13:
    void genRand(double offset_x = 0.0, double offset_y = 0.0);

This is the function:

LINE 84:
    void game::genRand(double offset_x = 0.0, double offset_y = 0.0) {
        perlin.SetFrequency(0.1);
        for(int _x=0; _x<dimensions.x/32; _x++){
            for(int _y=0; _y<dimensions.y/32; _y++){
                vec.push_back((perlin.GetValue(_x+offset_x, _y+offset_y, 0.2)+1.f)*2/2);
            }
        }
    }

Error:

make
g++ main.cpp -w -std=c++11 -lsfml-graphics -lsfml-window -lsfml-system -lnoise -o main
main.cpp:84:64: error: default argument given for parameter 1 of ‘void game::genRand(double, double)’ [-fpermissive]
 void game::genRand(double offset_x = 0.0, double offset_y = 0.0) {
                                                                ^
main.cpp:13:14: note: previous specification in ‘void game::genRand(double, double)’ here
         void genRand(double offset_x = 0.0, double offset_y = 0.0);
              ^
main.cpp:84:64: error: default argument given for parameter 2 of ‘void game::genRand(double, double)’ [-fpermissive]
 void game::genRand(double offset_x = 0.0, double offset_y = 0.0) {
                                                                ^
main.cpp:13:14: note: previous specification in ‘void game::genRand(double, double)’ here
         void genRand(double offset_x = 0.0, double offset_y = 0.0);
              ^

I don't understand what i did wrong.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 4
    Remove the defaults from the function definition. You only need them in the declaration. – juanchopanza Jan 11 '15 at 10:43
  • 2
    You specify default arguments in the declaration only, not in the definition (unless it's inline). – πάντα ῥεῖ Jan 11 '15 at 10:44
  • The default arguments are only in the declaration, when you define and implement the function the compiler already knows what the value should be (as the function itself, you only know that you get a value, the variable is always there)... – Zach P Jan 11 '15 at 10:49

1 Answers1

1

When you write the definition of a function (the body) separately , you should not bring default parameter any more.

In fact, Default parameter values must appear on the declaration, since that is the only thing that the caller sees.

It would be good practice to comment in the default values in the repeated function argument list:

void foo(int x = 42,
         int y = 21);

void foo(int x /* = 42 */,
         int y /* = 21 */)
{
   ...
}
Emadpres
  • 3,466
  • 2
  • 29
  • 44