How do I return element in an array thats inside a class?

I have a program where I roll a die X number of times and need to print how many times it lands on each side. I tried to create an array in the class aDie that increments each time the corresponding number is rolled but when I go to call and print it in the main my out put is 0. I just picked how many times it landed on the side 4 just to see if it works and it doesn't.

#define ADIE_H
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;

class aDie {
public:
int roll();
int count(int face);
aDie();
private:
int numRolled;
int countOfRoll[6];
};

aDie::aDie() {
int countOfRoll[5] = {0};
}

int aDie::roll() {
numRolled = (rand() % 6) + 1; //gets random number between 1 and 6
countOfRoll[numRolled]++; //increments element numRolled
return numRolled;
}

int aDie::count(int face) {
return countOfRoll[face];
}

int main() {
srand(time(NULL));
//srand(2);

int maxRolls = 10;
vector<int> totalRolls(maxRolls);
int i = 0;

aDie getRan;
for (i = 0; i < maxRolls; ++i) { // iterates loop maxRolls times
getRan.roll(); // gets random number
totalRolls.at(i) = getRan.roll();
cout << totalRolls.at(i) << endl;
}
getRan.count(4);
cout << " test " << getRan.count(4) << endl;

return 0;
}
Last edited on
Alice throws boiling water to Bob, the she asks Charlie if it hurts.
`getRan' and `getCount' are different objects.

Also, you need to initialize your variables. Set all the elements of the `countOfRoll' array to 0 (do it in the constructor)
Last edited on
I updated the original code to what you mentioned and now i'm getting 32769 as in my print at getRan.coun(4). What going wrong?
1
2
3
aDie::aDie() {
   int countOfRoll[5] = {0}; //this is a local variable, it is not your member variable
}


1
2
3
4
5
6
7
8
9
10
11
12
13
aDie::aDie():
   countOfRoll{0} //c++11
{
}

aDie::aDie()
{
   std::fill( //c++98 (or use a loop)
      this->countOfRoll,
      this->countOfRoll+6,
      0
   );
}


Edit: given that you are initializing to 0, you may to
1
2
3
4
aDie::aDie():
   countOfRoll() //c++03
{
}
http://stackoverflow.com/a/5602057
Last edited on
Topic archived. No new replies allowed.