### Outputting each instance value.

Hello I have a problem outputting each
value for the getIndvCost() function and I wanted to
see if anyone knew how to output them using pointers.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768`` ``````//John 3:16 #include #include #include #include "Stat.h" using namespace std; int main() { Statistics *people = nullptr; people = new Statistics[100]; srand (time(NULL)); for (Statistics *ptr = people; ptr < people + 100; ++ptr) { (*ptr).addPrice(rand() % 1000000 + 100000); } cout << fixed << setprecision(2) << endl; cout << "Statistics\n{\n"; for (Statistics *ptr = people; ptr < people + 100; ++ptr) { cout << setw(2) << "[" << setw(2) << ptr - people << "] = \$"; ptr->getIndvCost(); cout << endl; } cout << "}" << endl; cout << fixed << setprecision(2) << endl; cout << "Total price = \$" << (*people).getTotalCost() << endl; cout << "Total people = " << (*people).getCount() << endl; } Statistics.h ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Duetoronomy 4 #ifndef STAT_H #define STAT_H class Statistics { private: static double totalCost; static double peopleCount; int individualCost; public: Statistics() { peopleCount++; } void addPrice(double p) { individualCost += p; totalCost += p; } double getIndvCost() { return individualCost; } double getTotalCost() { return totalCost; } int getCount() { return peopleCount; } }; double Statistics::totalCost = 0; double Statistics::peopleCount = 0; #endif ``````
Last edited on
We can't tell what your program does without the definition of Statistics.
Fixed.
"that whoever believes in C++ shall not stagnate but will always be learning"

The `ptr->getIndvCost();` is like line 2 below:
 ``123`` ``````int main() { 42; }``````

No side-effects (and no output). On the other hand, `cout << ptr->getIndvCost();` ...
 `` `` ``(*ptr).addPrice(rand() % 1000000 + 100000);``

Alternative:

 `` `` ``ptr->addPrice(rand() % 1000000 + 100000);``

Last edited on
There is more than two valid syntaxes, are there?
 ``123456`` ``````(*ptr).addPrice(42); ptr->addPrice(42); ptr[0].addPrice(42); (*ptr+0).addPrice(42); (*0+ptr).addPrice(42); 0[ptr].addPrice(42);``````

If member function is declared `static`, then there is call without object too:
`Statistics::getTotalCost()`
Registered users can post here. Sign in or register to post.