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
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!
{{Short description|Capability of some programming languages}} {{multiple issues| {{cleanup-reorganize|date=October 2011}} {{refimprove|date=October 2011}} }} {{Confuse|Instruction overlapping|Overlay (programming)|Method overriding}} {{Polymorphism}} In some [[programming language]]s, '''function overloading''' or '''method overloading''' is the ability to create multiple [[subprogram|functions]] of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context. == Basic definition == For example, {{mono|doTask()}} and {{nowrap|{{mono|doTask(object o)}}}} are overloaded functions. To call the latter, an [[object (computer science)|object]] must be passed as a [[parameter (computer science)|parameter]], whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second function, which would result in an ''ambiguous call'' error, as the [[compiler]] wouldn't know which of the two methods to use. Another example is a {{nowrap|{{mono|Print(object o)}}}} function that executes different actions based on whether it's printing text or photos. The two different functions may be overloaded as {{nowrap|{{mono|Print(text_object T); Print(image_object P)}}.}} If we write the overloaded print functions for all objects our program will "print", we never have to worry about the type of the object, and the correct function call again, the call is always: {{mono|Print(something)}}. ==Languages supporting overloading== Languages which support function overloading include, but are not necessarily limited to, the following: * [[Ada (programming language)|Ada]] * [[Apex (programming language)|Apex]] * [[C++]] * [[C Sharp (programming language)|C#]] * [[Clojure]]<ref>{{Cite web |title=Clojure - Learn Clojure - Functions |url=https://clojure.org/guides/learn/functions#_multi_arity_functions |access-date=2023-06-13 |website=clojure.org}}</ref> * [[D (programming language)|D]] * [[Swift (programming language)|Swift]] * [[Fortran]] * [[Kotlin (programming language)|Kotlin]]<ref>{{cite web |title=Kotlin language specification |url=https://kotlinlang.org/spec/overload-resolution.html |website=kotlinlang.org}}</ref> * [[Java (programming language)|Java]]{{sfn|Bloch|2018|loc=§Chapter 8 Item 52: Eliminate unchecked warnings|p=238-244}} * [[Julia (programming language)|Julia]] * [[PostgreSQL]]<ref>{{Cite web|date=2021-08-12|title=37.6. Function Overloading|url=https://www.postgresql.org/docs/13/xfunc-overload.html|access-date=2021-08-29|website=PostgreSQL Documentation|language=en}}</ref> and [[PL/SQL]]<ref>{{Cite web|title=Database PL/SQL User's Guide and Reference|url=https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/subprograms.htm#i12352|access-date=2021-08-29|website=docs.oracle.com|language=en}}</ref> * [[Scala (programming language)|Scala]] * [[TypeScript]] * [[Visual Basic (.NET)]] * [[Wolfram Language]] * [[Elixir (programming language)|Elixir]] * [[Nim (programming language)|Nim]]<ref>{{cite web|title=Nim Manual|url=https://nim-lang.org/docs/manual.html#overloading-resolution|website=nim-lang.org|language=en}}</ref> * [[Crystal (programming language)|Crystal]]<ref>{{cite web|title=Crystal Docs|url=https://crystal-lang.org/reference/1.8/syntax_and_semantics/overloading.html|website=crystal-lang.org|language=en}}</ref> * [[Delphi (software)|Delphi]]<ref>{{cite web|title=Embarcadero Delphi|url=https://docwiki.embarcadero.com/RADStudio/Athens/en/Overloading|website=embarcadero.com|language=en}}</ref> * [[Python (programming language)|Python]] Languages that do not support function overloading include [[C (programming language)|C]], [[Rust (programming language)|Rust]] and [[Zig (programming language)|Zig]]. ==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. ==Constructor overloading== [[Constructor (object-oriented programming)|Constructors]], used to create instances of an object, may also be overloaded in some [[object-oriented]] [[programming language]]s. Because in many languages the constructor's name is predetermined by the name of the class, it would seem that there can be only one constructor. Whenever multiple constructors are needed, they are to be implemented as overloaded functions. In [[C++]], [[default constructor]]s take no parameters, instantiating the object [[Instance variable|members]] with their appropriate default values, "which is normally zero for numeral fields and empty string for string fields".<ref>{{cite book |last1=Chan |first1=Jamie |title=Learn C# in One Day and Learn It Well |date=2017 |isbn=978-1518800276 |page=82 |edition=Revised}}</ref> For example, a default constructor for a restaurant bill object written in C++ might set the tip to 15%: <syntaxhighlight lang=Cpp> Bill() : tip(0.15), // percentage total(0.0) { } </syntaxhighlight> The drawback to this is that it takes two steps to change the value of the created Bill object. The following shows creation and changing the values within the main program: <syntaxhighlight lang=Cpp> Bill cafe; cafe.tip = 0.10; cafe.total = 4.00; </syntaxhighlight> By overloading the constructor, one could pass the tip and total as parameters at creation. This shows the overloaded constructor with two parameters. This overloaded constructor is placed in the class as well as the original constructor we used before. Which one gets used depends on the number of parameters provided when the new Bill object is created (none, or two): <syntaxhighlight lang=Cpp> Bill(double tip, double total) : tip(tip), total(total) { } </syntaxhighlight> Now a function that creates a new Bill object could pass two values into the constructor and set the data members in one step. The following shows creation and setting the values: <syntaxhighlight lang=Cpp> Bill cafe(0.10, 4.00); </syntaxhighlight> This can be useful in increasing program efficiency and reducing code length. Another reason for constructor overloading can be to enforce mandatory data members. In this case the default constructor is declared private or protected (or preferably deleted since [[C++11]]) to make it inaccessible from outside. For the Bill above total might be the only constructor parameter{{snd}} since a Bill has no sensible default for total{{snd}} whereas tip defaults to 0.15. ==Complications== Two issues interact with and complicate function overloading: [[Name masking]] (due to [[Scope (computer science)|scope]]) and [[implicit type conversion]]. If a function is declared in one scope, and then another function with the same name is declared in an inner scope, there are two natural possible overloading behaviors: the inner declaration masks the outer declaration (regardless of signature), or both the inner declaration and the outer declaration are included in the overload, with the inner declaration masking the outer declaration only if the signature matches. The first is taken in C++: "in C++, there is no overloading across scopes."<ref name=bjarne_faq>{{cite web |url=http://www.stroustrup.com/bs_faq2.html#overloadderived| title=Why doesn't overloading work for derived classes? |last=Stroustrup |first=Bjarne |author-link=Bjarne Stroustrup}}</ref> As a result, to obtain an overload set with functions declared in different scopes, one needs to explicitly import the functions from the outer scope into the inner scope, with the {{code|using}} keyword. Implicit type conversion complicates function overloading because if the types of parameters do not exactly match the signature of one of the overloaded functions, but can match after type conversion, resolution depends on which type conversion is chosen. These can combine in confusing ways: An inexact match declared in an inner scope can mask an exact match declared in an outer scope, for instance.<ref name=bjarne_faq/> For example, to have a derived class with an overloaded function taking a {{code|double}} or an {{code|int}}, using the function taking an {{code|int}} from the base class, in C++, one would write: <syntaxhighlight lang=Cpp> class B { public: void F(int i); }; class D : public B { public: using B::F; void F(double d); }; </syntaxhighlight> Failing to include the {{code|using}} results in an {{code|int}} parameter passed to {{code|F}} in the derived class being converted to a double and matching the function in the derived class, rather than in the base class; Including {{code|using}} results in an overload in the derived class and thus matching the function in the base class. ==Caveats== If a method is designed with an excessive number of overloads, it may be difficult for developers to discern which overload is being called simply by reading the code. This is particularly true if some of the overloaded parameters are of types that are inherited types of other possible parameters (for example "object"). An IDE can perform the overload resolution and display (or navigate to) the correct overload. Type-based overloading can also hamper code maintenance, where code updates can accidentally change which method overload is chosen by the compiler.<ref>{{Cite web|url=https://gbracha.blogspot.fr/2009/09/systemic-overload.html|title=Systemic Overload|last=Bracha|first=Gilad|date=3 September 2009|author-link=Gilad Bracha|publisher=Room 101|publication-date=3 September 2009}}</ref> ==See also== * [[Abstraction (computer science)]] * [[Constructor (computer science)]] * [[Default argument]] * [[Dynamic dispatch]] * [[Factory method pattern]] * [[Method signature]] * [[Method overriding]] * [[Object-oriented programming]] * [[Operator overloading]] ==Citations== {{Reflist}} ==References== *{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}} ==External links== * {{cite journal |last=Meyer|first=Bertrand|author-link=Bertrand Meyer |date=October 2001 |title=Overloading vs Object Technology |url=http://se.ethz.ch/~meyer/publications/joop/overloading.pdf |journal=Journal of Object-Oriented Programming |volume=14 |issue=4 |access-date=27 August 2020 |department=Eiffel column |publisher=101 Communications LLC |pages=3{{ndash}}7 }} [[Category:Method (computer programming)]] [[Category:Articles with example C++ code]]
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)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite journal
(
edit
)
Template:Cite web
(
edit
)
Template:Code
(
edit
)
Template:Confuse
(
edit
)
Template:Distinguish
(
edit
)
Template:Mono
(
edit
)
Template:Multiple issues
(
edit
)
Template:Nowrap
(
edit
)
Template:Polymorphism
(
edit
)
Template:Rcatsh
(
edit
)
Template:Reflist
(
edit
)
Template:Sfn
(
edit
)
Template:Short description
(
edit
)
Template:Snd
(
edit
)