Hi, I'm struggling with a c++ class and haven't been able to find out why this function I've created (onHand) is always returning the value "1" instead of what I want (which is an array value * an array value).
No matter what I try, each time onHand is called from main.cpp it displays "1".
Any tips would be greatly appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
extern Coin coinArray;
I just realized the coin.cpp I posted contained incomplete code:
line 16 just has coinArray[i].Count * coinArray[i].Size
when I have Total += coinArray[i].Count * coinArray[i].Size instead, I get a compiler error about unidentified symbols for architecture x86_64 so I took it out just to get it compiling for now, but I don't understand why its always returning 1.
In the for loop of your function double onHand() you calculate the value for each coin but fail to add it to Total. The function is suppose to return a double value but there is no return statement. Add,
I am surprised that it compiles without a return statement.
Made some edits to the post above because you need to remember to include class name in class functions and I missed that at first (tired as hell). And yes, the line inside the for loop needs to be fixed as well but I'm not going to do it because it sounds like you are on the right track now.
One other thing I just noticed. In main.cpp line 26:
cout << "$" << onHand << " in machine." << endl;
You are not actually calling the function. You need onHand() with parenthesis to call the function. Without the parenthesis onHand is a pointer to the function. Since you never actually call the function that may explain why it compiles. The linker never tries to link to the function itself because it is never used.
was it because my array "coinArray" was in main and my onHand() function was trying to compute values that it didn't have access to?
It comes down to the linker not being able to "see" coinArray from Coin.cpp. When compiling onHand, your extern Coin coinArray; is basically telling the compiler that coinArray is defined someplace else and that it's up to the linker to find it later.
The reason that coinArray had to be in the global scope is so that its symbol would be exported. The way you had it was coinArray was a local variable. Local variables' symbols (i.e. names) aren't exported. Thus, the linker was not able to "see" coinArray.