Say you had two classes "TwoDice" and "Die". You want two Die objects to always be part of an instance of TwoDice, so you create two Die objects in the constructor.
TwoDice::TwoDice()
{
Die die1;
Die die2;
}
Then you call the TwoDice object's rollDice method which in turn calls on each individual Die's roll method.
bool TwoDice::rollDice()
{
faceValue1 = die1.roll();
faceValue2 = die2.roll();
}
Currently, the issue is that when I set it up this way, die1 and die2 are not defined which makes sense because those are just local variables within that constructor. However, when I made die1 and die2 specifically defined private variables for the TwoDice class, I received multiple compile errors. Is there a way I can make those two Die objects public so the other methods can access them?
Here's the TwoDice.cpp file:
// TwoDice.cpp: TwoDice class method definitions
#include "stdafx.h"
#include "time.h"
#include "TwoDice.h"
#include "Die.cpp"
#include "Die.h"
#include <cstdlib>
#include <iostream>
using namespace std;
TwoDice::TwoDice(void)
{
Die die1;
Die die2;
}
TwoDice::TwoDice(int d1, int d2)
{
Die die1(d1);
Die die2(d2);
}
void TwoDice::rollDice(void)
{
die1.roll();
die2.roll();
}
void TwoDice::getFaceValueDieOne(void)
{
faceValueDie1 = die1.getFaceValue();
}
void TwoDice::getFaceValueDieTwo(void)
{
faceValueDie2 = die2.getFaceValue();
}
bool TwoDice::isMatchingPair(void)
{
if(faceValueDie1 == faceValueDie2)
{
return true;
}
else
{
return false;
}
}
bool TwoDice::isSnakeEyes(void)
{
if(faceValueDie1 == 1 && faceValueDie2 == 1)
{
return true;
}
else
{
return false;
}
}
void TwoDice::display(void)
{
cout << "Die 1 = " << faceValueDie1 << endl;
cout << "Die 2 = " << faceValueDie2 << endl;
}
int TwoDice::getValueOfDice()
{
return faceValueDie1 + faceValueDie2;
}
And here's the TwoDice.h file:
// TwoDice.h: class definition file
#pragma once
class TwoDice
{
private:
int faceValueDie1;
int faceValueDie2;
public:
TwoDice();
TwoDice(int, int);
void rollDice();
void getFaceValueDieOne();
void getFaceValueDieTwo();
bool isMatchingPair();
bool isSnakeEyes();
void display();
int getValueOfDice();
};
Here is Die.cpp:
// Die.cpp: Die class method definitions
#include "stdafx.h"
#include "time.h"
#include "Die.h"
#include <cstdlib>
using namespace std;
Die::Die(void)
{
numSides = 6;
faceValue = 0;
srand((unsigned int)time(NULL));
}
Die::Die(int n)
{
numSides = n;
faceValue = 0;
srand((unsigned int)time(NULL));
}
int Die::roll()
{
faceValue = rand()%numSides + 1;
return faceValue;
}
int Die::getFaceValue()
{
return faceValue;
}
Here is Die.h:
// Die.h: class definition file
#pragma once
class Die
{
private:
int numSides;
int faceValue;
public:
Die();
Die(int n);
int roll();
int getFaceValue();
};