C++ Function Overloading with example

Posted on

 

 

C++ Perform Overloading

 

Perform Overloading

If any class have a number of features with identical names however completely different parameters then they’re stated to be overloaded. Perform overloading lets you use the identical identify for various features, to carry out, both identical or completely different features in the identical class.

Perform overloading is often used to reinforce the readability of this system. If it’s a must to carry out one single operation however with completely different quantity or forms of arguments, then you may merely overload the perform.


Methods to overload a perform

  1. By altering variety of Arguments.
  2. By having several types of argument.

Variety of Arguments completely different

In such a perform overloading we outline two features with identical names however completely different variety of parameters of the identical sort. For instance, within the beneath talked about program now we have made two sum() features to return sum of two and three integers.

Right here sum() perform is overloaded, to have two and three arguments. Which sum() perform will likely be known as, will depend on the variety of arguments.


Completely different Datatype of Arguments

In such a overloading we outline two or extra features with identical identify and identical variety of parameters, however the kind of parameter is completely different. For instance on this program, now we have two sum() perform, first one will get two integer arguments and second one will get two double arguments.


Default Arguments

Once we point out a default worth for a parameter whereas declaring the perform, it’s stated to be as default argument. On this case, even when we make a name to the perform with out passing any worth for that parameter, the perform will take the default worth specified.

Right here now we have supplied a default worth for y, throughout perform definition.

Output :

First two perform calls will produce the very same worth.

for the third perform name, y will take 10 as worth and output will turn out to be 20.

By setting default argument, we’re additionally overloading the perform. Default arguments additionally mean you can use the identical perform in numerous conditions similar to perform overloading.


Guidelines for utilizing Default Arguments

  1. Solely the final argument should be given default worth. You can’t have a default argument adopted by non-default argument.
  2. When you default an argument, then you’ll have to default all the next arguments after that.
  3. You can provide any worth a default worth to argument, appropriate with its datatype.

Placeholder Arguments

When arguments in a perform are declared with none identifier they’re known as placeholder arguments.

Such arguments will also be used with default arguments.