05 December 2012

Function overloading

Function overloading in an important concept in OOPS(Object Oriented Programming Concepts). In many technical interviews for Software Developer role, an interviewer will definitely ask questions on function overloading to test the basic understanding of the Object Oriented Programming concepts.

What is the significance of function overloading in OOPS and where its useful?

How can we achieve function overloading in .NET?

Will the return type variation in the method declaration also leads to function overloading?

Achieving ploymorphism using function overloading? Will it be compile time polymorphism or runtime polymorphism?

Without much ado, lets start understanding function overloading.

Function overloading means in a class there could be many functions with the same method name but with the varying number of parameters and their data types. i.e. name of the method we will invoke is same, but which implementation of the method is called depends on how many parameters we are passing and what are the data types of the parameters.

Always its better to start with an example.The below program code illustrate function overloading with varying number of parameters in the overloaded methods.

By looking at the above code and the program output, it is clear that depending on the number of parameters passed to the Add() method, a different implementation of the method with the equal number of parameters is executed.

Now let's have a look function overloading with the same number of parameters but with different parameters type.

Type Calculator' already defines a member called 'Add' with the same parameter types

The call is ambiguous between the following methods or properties: 'Calculator.Add(int, int)' and 'Calculator.Add(int, int)'

Because the binding to call which of the overloaded method to get executed is decided at the compile time and that is based on the parameters number and parameters data types. And hence function overloading is not depend on the return type of the method.

As we discussed using function overloading we can achieve compile time polymorphism. To know more on this read my another post, polymorphism types.