Function overloading and return type

In C++ and Java, functions can not be overloaded if they differ only in the return type.

For example, the following program C++ and Java programs fail in compilation.

C++ Program

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
int foo() { 
    return 10; 
}
  
char foo() {  // compiler error; new declaration of foo()
    return 'a'
}
  
int main()
{
    char x = foo();
    getchar();
    return 0;
}

chevron_right


Java Program

filter_none

edit
close

play_arrow

link
brightness_4
code

// filename Main.java
public class Main {
    public int foo() {
        return 10;
    }
    public char foo() { // compiler error: foo() is already defined
        return 'a';
    }
    public static void main(String args[])
    
    }
}

chevron_right


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


11


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.