Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function with less parameters than needed

I want to call a function ABC within another function XYZ but the parameters of the another function are not available except s. I don't even need them. My purpose will be solved with s only. But since I have declared the function with parameters s, t and u. And I need to declare like this because function ABC need them.

Now how to solve this problem.

bool ABC (int s, float t, int u)
{
     Function Implementation;
}

void XYZ (float a)
{
    Statement 1;
    Statement 2;

    if(ABC(s, t, u))
       Statement 3;

}

void main()
{
 Have parameters s, t, u and a with me.

//Call Function
  XYZ(a);

}
like image 511
hawkeye Avatar asked Jun 14 '26 16:06

hawkeye


1 Answers

You already have the bool ABC (int s, float t, int u) function. If you declare another function named ABC too with only one parameter(s in your case), then you can use any of those functions with the same name:

bool ABC (typename s)  //the return type can be anyithing, not necessarily bool
{
     Another Function Implementation;
}

Now you can use the ABC function with one parameter and you have another version with 3 parameters with the same function name. That is what function overload means in action.

if(ABC(s)) //ABC(s,t,u) would be working too
       Statement;

Note that the C++ language offers you a second way to handle optional parameters. By initializing the last n parameters with a specific value you will be able to leave some of them. In this case in the implementation of the function the left parameters will be assigned with the initial values:

bool ABC (int s, float t=0, int u=0)
{
     Function Implementation;
}

int main()
{
  //ABC() won`t work
  ABC(2) //s=2; t=0; u=0;
  ABC(2,3) //s=2; t=3; u=0;
  ABC(2,3,4) //s=2; t=3; u=4 
}

Be careful with that, because you can not set only s and u by calling the function with two paramaters. The order of parameters in your function declaration matters.

Furthermore assigning the parameters in your declaration with values which your function should not be got in normal way(these can be 0, INT_MIN (minimum value of a intiger value - defined in <climits>) or anything else depend on your problem) you can check easily in your implementation the number of parameters using for calling the function:

#include <climits>
#include <cfloats>

bool ABC (int s, float t=FLT_MAX, int u=INT_MAX)
{
   if(u == INT_MAX){...} //this means that you don`t set u

   if(t == FLT_MAX){...} //this means you set only s
}
like image 189
Dani Feldman Avatar answered Jun 17 '26 09:06

Dani Feldman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!