Did I get this right?

From a chapter on function overloading.

Exercise 9.2.1. Write two versions of a generic get_number() function so that
get_number can be used to get either an integer or floating-point number, as
desired. As with the get_int and get_dbl examples in this book, the function
should take a numeric argument that specifies the default value. Use the argu-
ment to determine what kind of data to return.

For example, given this call
get_number(0)
the function should return an integer value, whereas this call
get_number(0.0)
should return a value of type double. Remember that C++ notation recognizes
any constant expression with a decimal point as a floating-point expression with
double type.

1
2
3
4
5
6
7
8
9
int get_number(int n = 0) {
    cin >> n;
    return n;
}

float get_number(float n = 0.0) {
    cin >> n;
    return n;
}
1. Use double instead of float. There is never a reason to use float instead of double. This isn't wrong, though ;)

2. It mentions default value, but you have misinterpreted it I think. I think it means that, if the cin fails, you should clear cin's error state, so that it would be ready for the next attempt. Currently having = 0 and = 0.0 is pointless, because which version will be called if I write x = get_number(); ?
I'm not sure this'll work, because of the default values. Is the return type sufficient to distuingish two versions of a function? If you call get_number(), there is no way for the compiler to know which version you want, is there?
Gaminic: nope, that's right. the return value is not part of a function's signature in any language I know ;)
Topic archived. No new replies allowed.