I recently picked up C++ and decided to try out making a function. However, I've run into a problem with my function func()
where, even if declared beforehand, it only works if it's placed before the main()
function.
If I place it after the main()
function, the system tells me there is "no matching function for call to func
".
Note: the functionfunc2
on the other hand works even if placed before or after the main()
function.
So here's the code :
#include <stdio.h>
#include <iostream>
void func2();
int func();
int main()
{
int y=2;
std :: cout << "Hello World\n" << func(y) << "\n";
func2();
return 0;
}
int func(int x)
{
x *= 2;
return x;
}
void func2()
{
std :: cout << "Hello there";
}
In C language, the declaration int func();
means a function with an unspecified number of arguments of any type, returning a int
.
In C++ language, the same declaration int func();
means a function without any arguments, returning a int
.
And therefore, in C++, the definition of func
with an argument of type int
is an overload. For the compiler, it is a different function, which in the original code is not declared before use, so an error is emitted.
But in C, it would be perfectly legal.