Open In App

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 Program to demonstrate that function overloading
// fails if only return types are different
#include <iostream>
int fun() { return 10; }
  
char fun() { return 'a'; }
// compiler error as it is a new declaration of fun()
  
// Driver Code
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 Program to demonstrate that function overloading
// fails if only return types are different
  
// filename Main.java
public
class Main {
public
    int foo() { return 10; }
public
    char foo() { return 'a'; }
    // compiler error as it is a new declaration of fun()
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

Article Tags :