SHARE
HELP

### The Tradition of Sharing

#### Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.

To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

Authors:
Walter Savitch ,kenrick Mock
Chapter:
Polymorphism And Virtual Functions
Exercise:
Programming Projects
Question:7 | ISBN:9780132846813 | Edition: 5

### Question

The following lists a Dice class that simulates rolling a die with a different number of sides. The default is a standard die with six sides. The rollTwoDice function simulates rolling two dice objects and returns the sum of their values. The srand function requires including cstdlib.

class Dice

{

public:

Dice();

Dice( int numSides);

virtual int rollDice() const;

protected:

int numSides;

};

Dice::Dice()

{

numSides = 6;

srand(time(NULL)); // Seeds random number generator

}

Dice::Dice(int numSides)

{

this->numSides = numSides;

srand(time(NULL)); // Seeds random number generator

}

int Dice::rollDice() const

{

return (rand() % numSides) + 1;

}

// Take two dice objects, roll them, and return the sum

int rollTwoDice(const Dice& die1, const Dice& die2)

{

return die1.rollDice() + die2.rollDice();

}

Write a main function that creates two Dice objects with a number of sides of your choosing. Invoke the rollTwoDice function in a loop that iterates ten times and verify that the functions are working as expected.

Next create your own class, LoadedDice , that is derived from Dice . Add a default constructor and a constructor that takes the number of sides as input. Override the rollDice function in LoadedDice so that with a 50% chance the function returns the largest number possible (i.e., numSides ), otherwise it returns what Dice ’s rollDice function returns.

Test your class by replacing the Dice objects in main with LoadedDice objects. You should not need to change anything else. There should be many more dice rolls with the highest possible value. Polymorphism results in LoadedDice ’s rollDice function to be invoked instead of Dice ’s rollDice function inside rollTwoDice.

Sorry the answer is not available at the moment…

If you are able to find the answer, please make sure to post it here. So that your Juniors have smile on their lips and feel happy.