C++ Function Overloading with example

Posted on

 

 

C++ Perform Overloading

 

Perform Overloading

If any class have a number of capabilities with similar names however totally different parameters then they’re mentioned to be overloaded. Perform overloading permits you to use the identical identify for various capabilities, to carry out, both similar or totally different capabilities in the identical class.

Perform overloading is normally used to boost the readability of this system. If it’s important to carry out one single operation however with totally different quantity or varieties of arguments, then you possibly can merely overload the operate.


Methods to overload a operate

  1. By altering variety of Arguments.
  2. By having various kinds of argument.

Variety of Arguments totally different

In this sort of operate overloading we outline two capabilities with similar names however totally different variety of parameters of the identical sort. For instance, within the under talked about program we’ve got made two sum() capabilities to return sum of two and three integers.

Right here sum() operate is overloaded, to have two and three arguments. Which sum() operate might be known as, is dependent upon the variety of arguments.


Totally different Datatype of Arguments

In this sort of overloading we outline two or extra capabilities with similar identify and similar variety of parameters, however the kind of parameter is totally different. For instance on this program, we’ve got two sum() operate, first one will get two integer arguments and second one will get two double arguments.


Default Arguments

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

Right here we’ve got offered a default worth for y, throughout operate definition.

Output :

First two operate calls will produce the very same worth.

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

By setting default argument, we’re additionally overloading the operate. Default arguments additionally help you use the identical operate in several conditions identical to operate overloading.


Guidelines for utilizing Default Arguments

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

Placeholder Arguments

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

Such arguments can be used with default arguments.