Function Overloading and Return Type in C++
Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type.
Why is Function overloading not possible with different return types?
Function overloading comes under the compile-time polymorphism. During compilation, the function signature is checked. So, functions can be overloaded, if the signatures are not the same. The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded.
Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here.
Let’s understand this further through the following programs in C++ and Java:
C++ Program:
CPP
#include <iostream>
int fun() { return 10; }
char fun() { return 'a' ; }
int main()
{
char x = fun();
getchar ();
return 0;
}
|
Output
prog.cpp: In function ‘char fun()’:
prog.cpp:6:10: error: ambiguating new declaration of ‘char fun()’
char fun() { return 'a'; }
^
prog.cpp:4:5: note: old declaration ‘int fun()’
int fun() { return 10; }
^
Java Program:
Java
public
class Main {
public
int foo() { return 10 ; }
public
char foo() { return 'a' ; }
public
static void main(String args[]) {}
}
|
Output
prog.java:10: error: method foo() is already defined in class Main
char foo() { return 'a'; }
^
1 error
Last Updated :
03 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...