Function overloading in C++





c++ function overloading, function overloading c ++

Perhaps, someone from beginners scares the topic title “Function overloading”? Scares me. It seemed – It is something, what have long to understand. Actually, function overloading is very easy to understand. There is nothing complicated.

Overloaded functions – this function, that have the same name, but differ in the number of accepted parameters or types. Or – both.

To start to define what is the essence of the use of overloaded functions. It consists in the fact, you can give the same name functions. When this, they may be performed in various ways and various types of return values. For example, function should take an array of numbers and return the program to the sum of its elements. But we can pass in an array of function int or type double. In this case we can not provide different functions names. They're essentially performing the same work, just use different data types.

The following program defines three overloaded functions named sumElements(). All of them calculate the amount of array elements. One takes an array type int and its size. The second takes an array type double and its size. The third takes two array type elements int and double and their size.

Definitions of overloaded functions are located in the strings 31 – 61. They create a variable to store the sum of the values ​​of the array elements. In a for loop the amount of accumulated. Next, the resulting value is returned to the program, to place a call to an overloaded function.

Title to all three functions performed by one and the same name – strings 17, 21, 25. Passed to the function when calling an array of type int, and its size, the compiler will automatically detect, which of the three overloaded functions it is necessary to use. Similarly occur during call other functions.

c++ function overloading, function overloading c ++

The most important role in overloaded functions it plays a parameter list. It is also called a signature function. In order to use overloaded functions their signature must be different. Otherwise, the compiler will not be able to determine, what kind of function you want to use in a particular case,. That is, in the signature must be different number of parameters, types, or both, and the second.

How not to do:

c++ function overloading, function overloading c ++

With this announcement, even considering the fact, function that return data with different types of, and what the parameter names are different, the compiler can not determine which of the two functions cause. These signatures are identical in type and number of parameters. Therefore, these functions can not be overloaded.

Watch a short video about the overload:

Newsletter of programming:

Date
page
Function overloading in C++
Rating
51star1star1star1star1star

Leave a Reply

Place code in tags: <pre class="lang:c++ decode:true ">YOUR CODE</pre>