In some
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s, function overloading or method overloading is the ability to create multiple
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.
For example, and are overloaded functions. To call the latter, an
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
must be passed as a
parameter
A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
, 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
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
wouldn't know which of the two methods to use.
Another example is a function that executes different actions based on whether it's printing text or photos. The two different functions may be overloaded as 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: .
Languages supporting overloading
Languages which support function overloading include, but are not necessarily limited to, the following:
*
Apex
The apex is the highest point of something. The word may also refer to:
Arts and media Fictional entities
* Apex (comics), a teenaged super villainess in the Marvel Universe
* Ape-X, a super-intelligent ape in the Squadron Supreme universe
*Apex, ...
*
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
*
C#
*
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT, ...
* Fortran
*
Kotlin
*
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
*
PostgreSQL
PostgreSQL (, ), also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. It was originally named POSTGRES, referring to its origins as a successor to the In ...
and
PL/SQL
PL/SQL (Procedural Language for SQL) is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 6 - stored PL/SQL procedures/functions/packages/triggers since ...
*
Scala
*
TypeScript
TypeScript is a free and open source programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are ...
*
Wolfram Language
The Wolfram Language ( ) is a general multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary structures and data. It ...
*
Elixir
ELIXIR (the European life-sciences Infrastructure for biological Information) is an initiative that will allow life science laboratories across Europe to share and store their research data as part of an organised network. Its goal is to bring t ...
*
Nim
Rules in function overloading
* The same function name is used for more than one function definition
* The functions must differ either by the
arity
Arity () is the number of arguments or operands taken by a function, operation or relation in logic, mathematics, and computer science. In mathematics, arity may also be named ''rank'', but this word can have many other meanings in mathematics. In ...
or types of their parameters
It is a classification of static polymorphism in which a function call is resolved using some "best match" algorithm, where the particular function to call is resolved by finding the best match of the formal parameter types with the actual parameter types. The details of this algorithm vary from language to language.
Function overloading is usually associated with
statically-typed
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
programming languages that enforce
type checking
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
in
function call
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
s. An overloaded function is really just a set of different functions that happen to have the same name. The determination of which function to use for a particular call is resolved at
compile time
In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled.
The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
.
In
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
, function overloading is also known as compile-time polymorphism and static polymorphism.
Function overloading should not be confused with forms of
polymorphism where the choice is made at runtime, e.g. through
virtual function
In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part o ...
s, instead of statically.
Example: Function overloading in C++
#include
int Volume(int s)
double Volume(double r, int h)
long Volume(long l, int b, int h)
int main()
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
Constructors, used to create instances of an object, may also be overloaded in some
object-oriented
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pro ...
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
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++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
,
default constructor In computer programming languages, the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors (e.g. in Java), and is usually a nullary constructor. I ...
s take no parameters, instantiating the object
members
Member may refer to:
* Military jury, referred to as "Members" in military jargon
* Element (mathematics), an object that belongs to a mathematical set
* In object-oriented programming, a member of a class
** Field (computer science), entries in ...
with their appropriate default values, "which is normally zero for numeral fields and empty string for string fields". For example, a default constructor for a restaurant bill object written in C++ might set the tip to 15%:
Bill()
: tip(0.15), // percentage
total(0.0)
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:
Bill cafe;
cafe.tip = 0.10;
cafe.total = 4.00;
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):
Bill(double tip, double total)
: tip(tip),
total(total)
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:
Bill cafe(0.10, 4.00);
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
C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
) to make it inaccessible from outside. For the Bill above total might be the only constructor parameter since a Bill has no sensible default for total whereas tip defaults to 0.15.
Complications
Two issues interact with and complicate function overloading:
Name masking
In programming languages, name resolution is the resolution of the tokens within program expressions to the intended program components.
Overview
Expressions in computer programs reference variables, data types, functions, classes, objects, libr ...
(due to
scope
Scope or scopes may refer to:
People with the surname
* Jamie Scope (born 1986), English footballer
* John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution
Arts, media, and entertainment
* Cinem ...
) and
implicit type conversion
In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point valu ...
.
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 both 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."
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 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.
[
For example, to have a derived class with an overloaded function taking a or an , using the function taking an from the base class, in C++, one would write:
class B ;
class D : public B ;
Failing to include the results in an parameter passed to in the derived class being converted to a double and matching the function in the derived class, rather than in the base class; Including 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.
See also
* Abstraction (computer science)
In software engineering and computer science, abstraction is:
* The process of removing or generalizing physical, spatial, or temporal details or attributes in the study of objects or systems to focus attention on details of greater importance; ...
* Constructor (computer science)
In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required ...
* Dynamic dispatch
In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
* Factory method pattern
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by cr ...
* Method signature
* Method overriding
Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. In addition to ...
* Object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
* Operator overloading
In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is ...
References
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{{ndash7
Method (computer programming)
Articles with example C++ code