1

I am wondering why when I declare my function before the int main(), it works out fine however, when i try to do a prototype an call it I get an error - function does not take 0 arguments?

double timeOnHighway(double mileEndingPoint,
                     double mileStartingPoint,
                     double speed);

int main()
{
    cout << timeOnHighway();
    return 0;
}

double timeOnHighway(double mileEndingPoint = 20.0, 
                     double mileStartingPoint = 0.0,
                     double speed = 55.0)
{
    double timeTravel = ((mileEndingPoint - mileStartingPoint) / speed);
    return timeTravel;
}

AEM
  • 1,354
  • 8
  • 20
  • 30
  • https://stackoverflow.com/a/4989505/2027196 – JohnFilleau Apr 15 '20 at 23:11
  • 4
    Declare your default arguments in the declartion, not in the definition. – Cortex0101 Apr 15 '20 at 23:13
  • Does this answer your question? [Where to put default parameter value in C++?](https://stackoverflow.com/questions/4989483/where-to-put-default-parameter-value-in-c) – rsjaffe Apr 16 '20 at 00:40
  • Does this answer your question? [Default value of function parameter](https://stackoverflow.com/questions/2842928/default-value-of-function-parameter) – JaMiT Apr 16 '20 at 01:14

2 Answers2

4

Because the function (as declared by the prototype) does not take 0 arguments. In the main function, you're calling a function and passing in no arguments, but the compiler only sees the prototype, which takes 3 arguments. Thus the error. It doesn't know you're going to specialize it later with an implementation that can take zero arguments.

Moving the default arguments to the prototype (and later the .h file) will solve the problem.

samkass
  • 5,774
  • 2
  • 21
  • 25
2

default values have to be in the function declaration, not definition. Compiler takes the function definition before main and sees three parameters with no default values. Add them to the function declaration and remove from function definition, because default values should be "mentioned" only once in all function declarations and function definition.

  • 1
    Minor correction: The defaults can be in the definition because the definition is also a declaration. The important part is the default parameters need to be known before the compiler finds an invocation of the function that uses the default parameters. – user4581301 Apr 15 '20 at 23:20
  • Yeah, of course, if no previous function declaration available, default values can be placed in function definition, which is also a function declaration. – Александр Кушниренко Apr 15 '20 at 23:22