Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Function overloading
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Rules in function overloading== * The same function name is used for more than one function definition in a particular module, class or namespace * The functions must have different [[type signature]]s, i.e. differ in the number or the types of their formal parameters (as in C++) or additionally in their return type (as in Ada).<ref>{{cite book | last1 = Watt | first1 = David A. | last2 = Findlay | first2 = William | title = Programming Language Design Concepts | date = 1 May 2004 | publisher = John Wiley & Sons, Inc. | isbn = 978-0-470-85320-7 | pages = 204–207 }} </ref> Function overloading is usually associated with [[statically-typed]] programming languages that enforce [[type checking]] in [[function call]]s. An overloaded function is a set of different functions that are callable with the same name. For any particular call, the compiler determines which overloaded function to use and resolves this at [[compile time]]. This is true for programming languages such as Java.{{sfn|Bloch|2018|loc=§Chapter 8 Item 52: Use overloading judiciously|p=238-244}} Function overloading differs from forms of [[Polymorphism (computer science)|polymorphism]] where the choice is made at runtime, e.g. through [[virtual function]]s, instead of statically. '''Example: Function overloading in C++''' <syntaxhighlight lang=Cpp> #include <iostream> int Volume(int s) { // Volume of a cube. return s * s * s; } double Volume(double r, int h) { // Volume of a cylinder. return 3.1415926 * r * r * static_cast<double>(h); } long Volume(long l, int b, int h) { // Volume of a cuboid. return l * b * h; } int main() { std::cout << Volume(10); std::cout << Volume(2.5, 8); std::cout << Volume(100l, 75, 15); } </syntaxhighlight> In the above example, the volume of each component is calculated using one of the three functions named "volume", with selection based on the differing number and type of actual parameters.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)