tags:

views:

89

answers:

2

I forgot how to reference another function into a function in C++? In python it is declare as a class so that I can use it.

double footInches(double foot)
{
 double inches = (1.0/12.00) * foot;
 return inches;
}

double inchMeter(double inch)
{
 double meter = 39.37 * (footInches(inch));
 return meter;
}

I want to reference footInches in inchMeter.

edited

here is the main program

int main()
{
 double feet, inch, meter, x = 0;

 cout << "Enter distance in feet to convert it to meter: " << endl;
 cin >> x;

 cout << inchMeter(x);

 return 0;

i think the last line is not correct. i want to get the x in footInches first, then go to inchMeter, and then return the answer from inchMeter.

+1  A: 

By reference do you mean call?
You are calling the function correctly in your example, but you don't need the surrounding parenthesis.

So simply like this:

double inchMeter(double inch)
{
 double meter = 39.3700787 * footInches(inch);
 return meter;
}

If your functions exist in different .cpp files, or you need to reference a function that is defined later you can use a forward declaration.

Example:

a.cpp:

double footInches(double foot)
{
 double inches = foot * 12.0;
 return inches;
}

b.cpp:

double footInches(double foot); //This is a forward declaration

double inchMeter(double inch)
{
 double meter = 39.3700787 * footInches(inch);
 return meter;
}
Brian R. Bondy
hi, thanks. just edited my post. there is another prlbme
JohnWong
If it's easier for you, simply call footInches function, store the result then call the next inchMeters. Or combine the 2 calls like so: inchMeters(footInches(foot))
Brian R. Bondy
A: 

The traditional way to "reference" an arbitrary function in C is to use a function pointer. You really don't need it here because you're not going to change the implementation of the toinches function at runtime, but if you need a "reference to a function" you do it like this:

//Declare a function type that does what you want.
typedef double (*inch_converter_t)(double foot)

double footInches(double foot)
{
 double inches = (1.0/12.00) * foot;
 return inches;
};

//Pass a function pointer to another function for use.
double inchMeter(double inch, inch_converter_t converter)
{
 double meter = 39.37 * (converter(inch)); //Making a function call with the pointer.
 return meter;
}

int main()
{
    inch_converter_t myConverter = footInches;
    doube result = inchMeter(42, myConverter); //Call with function pointer.
}
Billy ONeal