Error in function overloading
I just started learning C++. Here is a code on the overloading of functions. My problem is I am unable to find the error. Can some one please help me on this?
Code:
# include <iostream>
# include <conio.h>
void test (int n = 0, float x = 2.5)
{
cout << "Function No. 1:";
cout << "n =" <<n << "x =" <<x << "\ n";
}
void test (float x = 4.1, int n = 2)
{
cout << "Function No. 2:";
cout<< "n= " <<n<< " x = " <<x<< " \n " ;
}
void main ()
{
int i = 5; float r = 3.2;
test (i, r) // function N1
test (r, i) // function N2
test (i) // function N1
test (r) // function N2
}
I get the error:
Quote:
18 C:\Users\Nas\Desktop\Projects\Exo 1.5\main.cpp `main' must return `int'
C:\Users\Nas\Desktop\Projects\Exo 1.5\Makefile.win [Build Error] [main.o] Error 1
Re: Error in function overloading
The compiler gives you the answer. The main () must return an integer, so ...
1 - you rename your main() into "int main ()"
2 - you put a "return 0" at the end, if you do not want to return anything
Re: Error in function overloading
"int f ()" indicates that the function "f ()" returns an int value. That is why we need to add a return statement at the end (eg return 0; means that the function returns the integer zero)
"void f ()" means that the function f () does not returns any value.
However the main function is a little different because it is the entry point of the program. Some compilers requires that a C++ program should return a value, so that's why it is necessary that the function main () returns an int.
Therefore the function "void main ()" is not legal in C++.
Re: Error in function overloading
One thing that should be understandable initially is that overloading function only works if you have a different number or types of arguments.
Thus, a surcharge may be in a form close to
Code:
void foo ()
void foo (int)
void foo (int, int)
but you can not consider overloading
Code:
void foo (int i = 3, int j = 4)
{
/ * What should be done * /
}
void foo (int i = 5, int j = 6)
because the number and type of argument is identical.
Remember that if you give default values for both arguments (as example), you find yourself in a reality with the option of using prototypes
Code:
void foo () / * the default values are used * /
void foo (int i) / * the default value of j is used * /
void foo (int i, int j) / * no default is used * /