Error in function caling

Write a function NumberOfPennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506.

For the above question, here is the code below.
Getting an error: `error: no matching function for call to 'NumberOfPennies(int)'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
   #include <iostream>
    using namespace std;

    int NumberOfPennies(int one,int two)
    {
     return (one*100+two);
    }

    int main() {
    cout << NumberOfPennies(5, 6) << endl; // Should print 506
    cout << NumberOfPennies(4) << endl;    // Should print 400
    return 0;
    }

However, when I put `int two=0` in the function `NumberOfPennies` it is working. Why is this so? Can anyone please explain this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
    using namespace std;

    int NumberOfPennies(int one,int two=0)
    {
     return (one*100+two);
    }

    int main() {
    cout << NumberOfPennies(5, 6) << endl; // Should print 506
    cout << NumberOfPennies(4) << endl;    // Should print 400
    return 0;
    }
Last edited on
you can default arguments, you can overload a function, or you can pass the value. What you cannot do is call the function with less parameters than it accepts without using a mechanism for doing so.

cout << NumberOfPennies(4,0) << endl; //pass the value

int NumberOfPennies(int one,int two = 0) //default value this is what you did. how this works is that if you do not give an input value for the second parameter, it uses the default. If you send a value, it over-rides the default. Defaulted parameters cannot come before non defaulted values, eg you can't say void foo (int x = 3, int y) //error, defaults come last

int NumberOfPennies(int one) //write this function, not a good option here, but if you did write it it would work.

it would be in your interest to learn to use meaningful names. try dollars and cents instead of one and two, for example, and it becomes so much easier to read. As you get into more complex things, this ability to read and understand the code becomes critical.
Last edited on
@Jonnin Since there is no second parameter in the second calling function, I need to set the second parameter in the function NumberOfPennies as 0
Topic archived. No new replies allowed.