Programming Search⌘K

Conceptcore

Overloading

Also called function overloading, method overloading, overload resolution.

Overloading gives one name to several functions that differ in the number or the types of their parameters. At each call, the language picks one of them from the arguments.

Applies to
core-languages

Idea

Overloading lets a program define several functions with the same name. The functions differ in the number or the types of their parameters. At each call, the language uses the arguments to pick one of them.

Wikipedia defines function overloading as "the ability to create multiple functions of the same name with different implementations."1 The functions "must have different type signatures, 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)."1

public class Main {
    static String show(int x) {
        return "int " + x;
    }

    static String show(String s) {
        return "string " + s;
    }

    static String show(int x, int y) {
        return "two ints " + x + " " + y;
    }

    public static void main(String[] args) {
        System.out.println(show(42));
        System.out.println(show("hi"));
        System.out.println(show(3, 4));
    }
}
Output
int 42
string hi
two ints 3 4

The three functions have the name show, and each has a different Function signature. The compiler reads the number and the types of the arguments in each call and picks the function that matches.

How it works

  1. The overload set. The functions with the same name that are visible at the call make the overload set. In Java, if two methods of a class "have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded."2
  2. The signature. The parameters tell the overloads apart. In C#, "The signature of a method consists of the name of the method, the number of type parameters, and the type and parameter-passing mode of each of its parameters, considered in the order left to right."3 The return type is not in this list. Java also says: "There is no required relationship between the return types or between the throws clauses of two methods with the same name, unless their signatures are override-equivalent."2
  3. The resolution. At each call, the compiler collects the candidate functions, removes the ones that the arguments cannot match, and then chooses the best of the rest4. cppreference says: "In simple terms, the overload whose parameters match the arguments most closely is the one that is called."4
  4. Compile time. The choice uses the types that the compiler knows. In Java, "the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked"2. Wikipedia says: "For any particular call, the compiler determines which overloaded function to use and resolves this at compile time."1
  5. No match or a tie. If no function matches the arguments, or two functions match equally well, the call does not compile. See the pitfall on ambiguous calls below.

In languages

LanguageVerdictNote
PythonStandard library
C++Native
JavaNative
CIdiom
C#Native
JavaScriptAbsent
TypeScriptNative
GoAbsent
RustIdiom
KotlinNativeKotlin functions and constructors can be overloaded by their parameter types. No example file exists because kotlinc is not installed.
SQLDoes not applyStandard SQL queries do not declare functions. Some databases allow overloaded user-defined functions in their own procedural languages.
BashAbsent
PowerShellNativeThe methods of a PowerShell class can be overloaded. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is a markup language and has no functions.
CSSDoes not applyCSS has no user-defined functions that a style sheet can overload.
Regular expressionsDoes not applyA regular expression has no functions.
  • Python. Python has no overloading1. A def statement is executed, and "Its execution binds the function name in the current local namespace to a function object"5. So a second def with the same name replaces the first. The typing.overload decorator describes several signatures for a type checker only: "@overload-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-@overload-decorated definition."6 The standard library also has functools.singledispatch, which will "Transform a function into a single-dispatch generic function."7 It chooses an implementation at run time: "When called, the generic function dispatches on the type of the first argument"7.
  • JavaScript. JavaScript has no overloading. A second function declaration with the same name replaces the first. MDN shows function a(b) {} followed by function a(b, c) {}, and then a.length is 28. One function checks the number and the types of its arguments.
  • TypeScript. TypeScript adds overloads to the types: "In TypeScript, we can specify a function that can be called in different ways by writing overload signatures."9 The program writes one body after the overload signatures, and "Functions have an implementation signature, but this signature can’t be called directly."9
  • Java. Methods and constructors can be overloaded. Constructors, "Like methods, they may be overloaded"2. The compiler chooses the overload2.
  • C#. "Overloading of methods permits a class, struct, or interface to declare multiple methods with the same name, provided their signatures are unique within that class, struct, or interface."3
  • C. C has no overloading1. C11 added the generic selection _Generic, which "Provides a way to choose one of several expressions at compile time, based on a type of a controlling expression"10. A macro with _Generic can send a call to a different function for each argument type.
  • C++. Free functions, member functions, constructors and operators can be overloaded. The compiler runs overload resolution at each call4.
  • Go. Go has no overloading. The Go FAQ says: "Method dispatch is simplified if it doesn’t need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice."11 A Go program gives each function a different name.
  • Rust. Rust has no overloading1. The Rust example on this page defines a trait with one method and implements the trait for each argument type.
  • Bash. A function declaration has no parameter list: "fname () compound-command [ redirections ]"12. The arguments "become the positional parameters during its execution"12. So a Bash function cannot have overloads. One function checks $# and the values of its arguments.
PythonGitHub
from functools import singledispatch


@singledispatch
def show(x, y=None):
    raise TypeError(f"no overload for {type(x).__name__}")


@show.register
def _(x: int, y=None):
    if y is None:
        return f"int {x}"
    return f"two ints {x} {y}"


@show.register
def _(x: str, y=None):
    return f"string {x}"


print(show(42))
print(show("hi"))
print(show(3, 4))
Output
int 42
string hi
two ints 3 4
  • Verdict: stdlib. Python has no overloading. functools.singledispatch chooses an implementation from the type of the first argument at run time, and a default value covers the second argument.
#include <iostream>
#include <string>

std::string show(int x) {
    return "int " + std::to_string(x);
}

std::string show(const std::string& s) {
    return "string " + s;
}

std::string show(int x, int y) {
    return "two ints " + std::to_string(x) + " " + std::to_string(y);
}

int main() {
    std::cout << show(42) << "\n";
    std::cout << show("hi") << "\n";
    std::cout << show(3, 4) << "\n";
}
Output
int 42
string hi
two ints 3 4
  • Verdict: native. The three free functions have the same name. Overload resolution chooses one at each call.
JavaGitHub
public class Main {
    static String show(int x) {
        return "int " + x;
    }

    static String show(String s) {
        return "string " + s;
    }

    static String show(int x, int y) {
        return "two ints " + x + " " + y;
    }

    public static void main(String[] args) {
        System.out.println(show(42));
        System.out.println(show("hi"));
        System.out.println(show(3, 4));
    }
}
Output
int 42
string hi
two ints 3 4
  • Verdict: native. The three methods have the same name and different parameter lists. The compiler chooses one at each call.
#include <stdio.h>

static void show_int(int x) {
    printf("int %d\n", x);
}

static void show_str(const char *s) {
    printf("string %s\n", s);
}

static void show_two_ints(int x, int y) {
    printf("two ints %d %d\n", x, y);
}

#define show(x) _Generic((x), int: show_int, char *: show_str, const char *: show_str)(x)

int main(void) {
    show(42);
    show("hi");
    show_two_ints(3, 4);
    return 0;
}
Output
int 42
string hi
two ints 3 4
  • Verdict: idiom. C has no overloading. The _Generic selection in the macro show chooses a function from the type of the argument at compile time. The two-argument case needs its own name.
using System;

class Program
{
    static string Show(int x)
    {
        return "int " + x;
    }

    static string Show(string s)
    {
        return "string " + s;
    }

    static string Show(int x, int y)
    {
        return "two ints " + x + " " + y;
    }

    static void Main()
    {
        Console.WriteLine(Show(42));
        Console.WriteLine(Show("hi"));
        Console.WriteLine(Show(3, 4));
    }
}
Output
int 42
string hi
two ints 3 4
  • Verdict: native. The three methods have the same name and different signatures. The compiler chooses one at each call.
JavaScriptGitHub
function show(x, y) {
  if (typeof x === "string") {
    return `string ${x}`;
  }
  if (y === undefined) {
    return `int ${x}`;
  }
  return `two ints ${x} ${y}`;
}

console.log(show(42));
console.log(show("hi"));
console.log(show(3, 4));
Output
int 42
string hi
two ints 3 4
  • Verdict: absent. JavaScript has no overloading. One function checks the number of arguments and the type of the first one.
TypeScriptGitHub
function show(x: number): string;
function show(x: string): string;
function show(x: number, y: number): string;
function show(x: number | string, y?: number): string {
  if (typeof x === "string") {
    return `string ${x}`;
  }
  if (y === undefined) {
    return `int ${x}`;
  }
  return `two ints ${x} ${y}`;
}

console.log(show(42));
console.log(show("hi"));
console.log(show(3, 4));
Output
int 42
string hi
two ints 3 4
  • Verdict: native. The overload signatures give the type checker three ways to call show. One implementation handles all of them, and callers cannot call the implementation signature.
package main

import "fmt"

func showInt(x int) string {
	return fmt.Sprintf("int %d", x)
}

func showString(s string) string {
	return "string " + s
}

func showTwoInts(x, y int) string {
	return fmt.Sprintf("two ints %d %d", x, y)
}

func main() {
	fmt.Println(showInt(42))
	fmt.Println(showString("hi"))
	fmt.Println(showTwoInts(3, 4))
}
Output
int 42
string hi
two ints 3 4
  • Verdict: absent. Go has no overloading, so each function gets its own name.
RustGitHub
trait Show {
    fn show(&self) -> String;
}

impl Show for i32 {
    fn show(&self) -> String {
        format!("int {}", self)
    }
}

impl Show for &str {
    fn show(&self) -> String {
        format!("string {}", self)
    }
}

impl Show for (i32, i32) {
    fn show(&self) -> String {
        format!("two ints {} {}", self.0, self.1)
    }
}

fn main() {
    let n: i32 = 42;
    let pair: (i32, i32) = (3, 4);
    println!("{}", n.show());
    println!("{}", "hi".show());
    println!("{}", pair.show());
}
Output
int 42
string hi
two ints 3 4
  • Verdict: idiom. Rust has no overloading. The trait Show has one method, and each argument type, including the tuple (i32, i32), implements it.
BashGitHub
show() {
  if [ "$#" -eq 2 ]; then
    echo "two ints $1 $2"
  elif [[ $1 =~ ^-?[0-9]+$ ]]; then
    echo "int $1"
  else
    echo "string $1"
  fi
}

show 42
show hi
show 3 4
Output
int 42
string hi
two ints 3 4
  • Verdict: absent. Bash functions have no parameter list, so they cannot be overloaded. One function checks $# and the form of its first argument.
  • Operator overloading. Many languages also let a program give a new meaning to an operator for its own types. In ALGOL 68, "The programmer may define new operators and both those and the pre-defined ones may be overloaded and their priorities may be changed by the coder."13 See Operator overloading and Overload an operator.
  • Overloading on the return type. Ada can also tell overloads apart by their return type1. Java, C# and C++ cannot23.
  • Default parameter values. A default value can replace an overload that only skips a parameter. The Kotlin documentation says: "Optional parameters reduce the need for multiple overloads, since you don't have to declare different versions of a function just to allow skipping a parameter with a reasonable default."14
  • Union types. In TypeScript, one signature with a union type is often simpler than several overloads. The handbook says: "Always prefer parameters with union types instead of overloads when possible"9.
  • Overloading and overriding. Overloading chooses a function at compile time. Overriding chooses a method at run time from the type of the receiver. Wikipedia says: "Function overloading differs from forms of polymorphism where the choice is made at runtime, e.g. through virtual functions, instead of statically."1 See Dynamic dispatch and Double dispatch.
  • Generic functions. A generic function has one body that works for many types. An overloaded name has one body for each signature. See Generics.

Pitfalls

Java chooses the overload from the static type

The compiler chooses the overload from "the compile-time types of the arguments"2, not from the class of the object at run time:

This code runs but gives a wrong answer on purpose.

public class Main {
    static String show(Object o) {
        return "object";
    }

    static String show(String s) {
        return "string";
    }

    public static void main(String[] args) {
        Object x = "hi";
        System.out.println(show(x));
    }
}
Output
object

The variable x has the type Object, so the call uses show(Object), though the value is a String. To choose by the type at run time, put the behavior in a method of the class and override it. See Dynamic dispatch.

A second def replaces the first in Python

Python executes each def and binds the name again5. The second area replaces the first:

This code runs but gives a wrong answer on purpose.

def area(side):
    return side * side


def area(width, height):
    return width * height


print(area(3, 4))
try:
    print(area(5))
except TypeError as e:
    print(e)
Output
12
area() missing 1 required positional argument: 'height'

Use one function with a default value, as in def area(width, height=None), or use functools.singledispatch to choose by type7.

Ambiguous calls

A call can match two overloads equally well. cppreference gives this example4:

void f(long);
void f(float);

f(0L); // calls f(long)
f(0);  // error: ambiguous overload

The literal 0 is an int. It is not a long and not a float, and the compiler finds no single best function4. Wikipedia names the causes: "Two issues interact with and complicate function overloading: Name masking (due to scope) and implicit type conversion."1 Many overloads also make code hard to read: "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."1

Cost

In Java, C# and C++, the compiler chooses the overload24. The program then makes a normal call, so overloading adds no cost at run time. It adds work for the compiler and for the reader. functools.singledispatch in Python chooses at run time from the type of the first argument7, so each call does a lookup first. The Go designers left overloading out partly for this reason: "Method dispatch is simplified if it doesn’t need to do type matching as well."11

History

ALGOL 68 had overloaded operators. "On 20 December 1968, the language was formally adopted by the group"13, and its programmers could define operators and overload them13. Ada, C++, Java and C# overload functions and methods by their parameters123. Later languages such as Go and Rust left overloading out111.

References

  1. Function overloading, Wikipedia, the introduction; Rules in function overloading; Complications; Caveats
  2. Classes, The Java Language Specification, Java SE 25 Edition, 8.4.9 Overloading
  3. Basic concepts, C# language specification, 7.5 Signatures and overloading
  4. Overload resolution, C++ reference, cppreference.com, the introduction
  5. Compound statements, The Python Language Reference, 8.7 Function definitions
  6. typing, Support for type hints, The Python Standard Library, typing.overload
  7. functools, Higher-order functions and operations on callable objects, The Python Standard Library, functools.singledispatch
  8. function, MDN Web Docs JavaScript Reference, Redeclarations
  9. More on Functions, The TypeScript Handbook, Function Overloads
  10. Generic selection, C reference, cppreference.com, the introduction
  11. Frequently Asked Questions, The Go Programming Language, Why does Go not support overloading of methods and operators?
  12. Shell Functions, Bash Reference Manual, 3.3 Shell Functions
  13. ALGOL 68, Wikipedia, History; Operators
  14. Functions, Kotlin Documentation, Parameters with default values

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/ZDBXDA/text.yaml