Kar Wai Kar Wai - 3 months ago 7
C++ Question

Function sum with first value for 3 times instead of other 2 values

I want the code to sum up all three numbers with the loop but the function just sum up the total amount with the first value for three times please help.

#include <iostream>
using namespace std;
class TEST
{
int num;
public:
void input()
{
cin>>num;
}
int getAmount()
{
return num;
}
};
float getTotalAmount(TEST *obj)
{
static float totalamount=0;
totalamount = totalamount + obj->getAmount();
return totalamount;
}
int main()
{
TEST obj[3];

for(int i=0;i<3;i++)
{
cout<<"Enter Number["<<i+1<<"]:";
obj[i].input();
cout<<"Current total= "<<getTotalAmount(obj)<<endl;
}
}

Answer

When you have an array, like

TEST obj[3];

using just the array name like obj makes it decay to a pointer to its first element.

So in the loop you are calling getTotalAmount with a pointer to the same object (obj[0]) all the time.

If you want to call the function for the different objects, either use &obj[i] or obj + i.

Comments