Function parameters

How to pass a functions as a parameter and use the values in it?

I am trying to develop a billing system, i have about 12 function. 1 function for each food type there are six food types and other are like search, about us etc functions., I have calculated the price and the quantity need in the food functions. I want to pass it to the invoice function. There are lot of data I want to pass like the item code, unit price, quantity, item name etc in one function. Since there are 6 functions it is difficult to do that so. Is it possible to pass a function as a parameter and take all the necessary values from it.
Last edited on
You can use functions as arguments for another function such as:
1
2
3
4
5
6
7
int calcArea();
void DisplayArea(int area);

int main ()
{
   DisplayArea(CalcArea());
}


However the way you have explained you are doing it seems very un necessary. You could have a single function for all the different types of food by creating some variable that reprents food type (such as an enumerator). This would mean you no longer need 6 function for 6 types of food. Even if you managed to get it to work your program would not be very scalabe. Think of a massive version of your program that people use all the time (like an online ordering system) it wouldnt be very scalable to have a function for each type of food. If you want more help you are going to have to explain your problem more and give code for us to read.
Last edited on
@aazir : Use a structure in which you'll pack all your data.

@martianxx : Your example has nothing to do with passing functions as arguments. You're passing the return value of a function, which is a completely different thing.
Sorry I thought the return value was what he wanted. If you want to pass the actual function then you do it in the following way by passing a pointer to the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

void DoSomething(void (f*)(void));
void HelloWorld();

int main()
{
   DoSomething(HelloWorld);
   return 0;
}
void DoSomething(void (f*)(void))
{
   (*f)();
}
void HelloWorld()
{
   cout << "Hello World" << endl;
}


As said using structures would significantly reduce the complexity. Plus you can pass the structure instance like any other variable type.
Thank You!!!
Topic archived. No new replies allowed.