Why Can’t We Overload Functions/Methods Based On Their Return Type (in C++/Java)?
I won’t go deeper into ‘What Function Overloading actually is’, but just a short definition for our discussion purpose-
What is Function Overloading? Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.
So, as we can see it’s just a feature by which we can use a same function name (with different signatures) for accomplishing different tasks. But the point that we need to keep in our mind is- It’s a Compile-Time Polymorphism, that means during the compilation of our code it is decided which one to call among all other overloaded versions. So, the compiler is not aware of the function body and what is actually going to be returned from the function (after the execution), because the return type that we have mentioned (in the function prototype) that may or may not be the proper one, as there can be some kind of implicit typecasting that may happen inside the function body, so it’d be difficult for a compiler to determine which function to call based on the return type only. So, it would create ambiguity in runtime (because, our program is indeed allowed to perform possible typecasting), that means we can’t be strict on the return type. So, isn’t it better to restrict doing function overloading based on return type and show an error message in Compile Time rather than Runtime error?
Here’s what compiler shows when we try to do this-
You may think, the 1st one should call the first version and the 2nd one should call the 2nd version as the variables in which I’m storing the returned values they are of type ‘int’ and ‘float’ respectively. But, isn’t a=10 is acceptable in both ‘int’ and ‘float’ data-types? So, why create ambiguity?
Hey, did you like the explanation?
If yes then don’t forget to follow exploreIT as I regularly come up with interesting topics related to programming. And of course, if you have any difficulty understanding the concepts or find anything wrong in the article please feel free to comment below!
Feet free to connect — https://www.linkedin.com/in/salman-shaikh-82989b1b9/
See you in the next article, Bye Bye!