Overloading

Function Overloading

Overloading a function is having the same name for multiple functions but with different arguments.

C doesn't support function overloading so the following code won't compile.

void foo() { printf ("foo()\n"); }

void foo(int n) { printf ("foo(%d)\n", n); }

C++ does support function overloading so the above does compile. Using the gcc compiler we can see what happens now.

void foo() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
void foo(int n) { std::cout << __PRETTY_FUNCTION__ << std::endl; }

int main() {
    foo(12);
    foo();
}

output

void foo(int)
void foo()

Default parameters

Default params can be use in next to the arg type. If the value was not given the default will be what was specified

output

But how does the compiler know which function to call?

output

Notice that here we were able to confuse the compiler. power(2, -3) should have called the uint function

Overload resolution

Overload resolution is the way the compilers knows which function to call (but its not perfect).

  • Step 1: Find all functions with same name

  • Step 2: functions with the correct number of args

  • Step 3: choose function with best matching arguments

doctest.h

A simple tester written by Viktor Kirilov. Here is a simple example

Last updated