Posted January 9, 2011 by Spyros in C/C++ Programming

What is Function Overloading && How to Use it to Write Better Code


C++ is all about making C programmers lives easier. Function overloading is one more C++ feature that presented a nice technique for writing better and more managed code.

What is Operator Overloading ?

Imagine a function like “int sum(int x, int y)”. This one calculates the sum of two numbers. This works fine for 2 numbers, but what happens if we need to add 3 ? Well, a good way to do it would be to just execute the sum function twice, wouldn’t it ? However, if we only needed to make a sum of 2 and 3 numbers, we could do something more elegant. The idea is to create 2 different versions of the same function. (Notice that we could also use variable arguments in this example, i will refer to that in another tutorial). Let’s take a look at an actual program that does that :

#include <iostream>
using namespace std;

int sum(int x, int y);
int sum(int x, int y, int z);

int sum(int x, int y)
    return x + y;

int sum(int x, int y, int z)
    return x + y + z;

int main()
    int two = sum(3, 5);
    int three = sum(3, 5, 2);

    cout << two << ' ' << three << endl;
    return 0;

Pay attention to the fact that you cannot overload the return value of a function because the C++ linker will complain. Only arguments can be overloaded. Function overloading is also many times seen in constructors of classes, just because there are many times that we need different initialization of an object. Of course, the constructor can only have one name, so the best way to do it is overload the constructor. This is a technique that you will encounter pretty often.