Function overloading program not working

OK, so I'm learning about overloading funtions to a very basic level. My understanding of it is that multiple functions can be given the same identifier but a different definition. When the function is called the compiler analyses the variables in amount and type and matches those variables to the correct function so that the output is of the right type.

I wrote a very basic program that asks for the user to input two values which are then summed with an add function. The program requires that the variables be either of int or double type and yet at runtime, if a number with a decimal is written when the first value is requested, the second level of input is skipped and the output displays a very long negative number. I can't figure out where I've gone wrong as it all seems to be correct as per my understanding. If someone could point out my mistake to get the program working I would appreciate it greatly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

int add(int a, int b)
{
	return a+b;
}

double add(double a, double b)
{
	return a+b;
}

int main(void)
{
	using std::cout;
	using std::cin;

	int number1;
	int number2;

	cout << "This program will sum two numbers and return the value with\nthe correct data type.\n";
	cout << "Please enter the first number to be summed: ";
	cin >> number1;
	cout << "\nPlease enter the second number to be summed: ";
	cin >> number2;
	cout << "\n\nThe answer is: " << add(number1, number2) << "\n\n";

	return 0;
}
You only ever ask for an integer, so if the user types in a double it will only read the integer part - which is what your program is asking for.
this is just an error in your reading.
the overloads are fine.

number1 and number2 are ints.
cin >>
ignores the decimal because it expects an int.

user input is full of traps.
you would need to parse it yourself
yeah, I just noticed that I set the input asked for to int. Silly old me, should have been more careful. Thanks anyway people!
Topic archived. No new replies allowed.