Search

11.x — Chapter 11 comprehensive quiz

Summary

Inheritance allows us to model an is-a relationship between two objects. The object being inherited from is called the parent class, base class, or superclass. The object doing the inheriting is called the child class, derived class, or subclass.

When a derived class inherits from a base class, the derived class acquires all of the members of the base class.

When a derived class is constructed, the base portion of the class is constructed first, and then the derived portion is constructed. In more detail:

  1. Memory for the derived class is set aside (enough for both the base and derived portions).
  2. The appropriate derived class constructor is called.
  3. The base class object is constructed first using the appropriate base class constructor. If no base class constructor is specified, the default constructor will be used.
  4. The initialization list of the derived class initializes members of the derived class.
  5. The body of the derived class constructor executes.
  6. Control is returned to the caller.

Destruction happens in the opposite order, from most-derived to most-base class.

C++ has 3 access specifiers: public, private, and protected. The protected access specifier allows the class the member belongs to, friends, and derived classes to access the protected member, but not the public.

Classes can inherit from another class publicly, privately, or protectedly. Classes almost always inherit publicly.

Here’s a table of all of the access specifier and inheritance types combinations:

Access specifier in base class Access specifier when inherited publicly Access specifier when inherited privately Access specifier when inherited protectedly
Public Public Private Protected
Private Inaccessible Inaccessible Inaccessible
Protected Protected Private Protected

Derived classes can add new functions, change the way functions that exist in the base class work in the derived class, change an inherited member’s access level, or hide functionality.

Multiple inheritance enables a derived class to inherit members from more than one parent. You should avoid multiple inheritance as much as possible.

Quiz time

Question #1


For each of the following programs, determine what they output, or if they would not compile, indicate why. This exercise is meant to be done by inspection, so do not compile these (otherwise the answers are trivial).

a)

Show Solution

b) Hint: Local variables are destroyed in the opposite order of definition.

Show Solution

c)

Show Solution

d)

Show Solution

e)

Show Solution

Question #2


a) Write an Apple class and a Banana class that are derived from a common Fruit class. Fruit should have two members: a name, and a color.

The following program should run:

And produce the result:

My apple is red.
My banana is yellow.

Show Solution

b) Add a new class to the previous program called GrannySmith that inherits from Apple.

The following program should run:

And produce the result:

My apple is red.
My banana is yellow.
My granny smith apple is green.

Show Solution

Question #3


Challenge time! The following quiz question is more difficult and lengthy. We're going to write a simple game where you fight monsters. The goal of the game is to collect as much gold as you can before you die or get to level 20.

Our program is going to consist of 3 classes: A Creature class, a Player class, and a Monster class. Player and Monster both inherit from Creature.

a) First create the Creature class. Creatures have 5 attributes: A name (std::string), a symbol (a char), an amount of health (int), the amount of damage they do per attack (int), and the amount of gold they are carrying (int). Implement these as class members. Write a full set of getters (a get function for each member). Add three other functions: void reduceHealth(int) reduces the Creature's health by an integer amount. bool isDead() returns true when the Creature's health is 0 or less. void addGold(int) adds gold to the Creature.

The following program should run:

And produce the result:

The orc has 3 health and is carrying 15 gold.

Show Solution

b) Now we're going to create the Player class. The Player class inherits from Creature. Player has one additional member, the player's level, which starts at 1. The player has a custom name (entered by the user), uses symbol '@', has 10 health, does 1 damage to start, and has no gold. Write a function called levelUp() that increases the player's level and damage by 1. Also write a getter for the level member. Finally, write a function called hasWon() that returns true if the player has reached level 20.

Write a new main() function that asks the user for their name and produces the output as follows:

Enter your name: Alex
Welcome, Alex.
You have 10 health and are carrying 0 gold.

Show Solution

c) Next up is the Monster class. Monster also inherits from Creature. Monsters have no non-inherited member variables.

First, write an empty Monster class inheriting from Creature, and then add an enum inside the Monster class named Type that contains enumerators for the 3 monsters that we'll have in this game: DRAGON, ORC, and SLIME (you'll also want a max_types enumerator, as that will come in handy in a bit).

Show Solution

d) Each Monster type will have a different name, symbol, starting health, gold, and damage. Here is a table of stats for each monster Type:

Type Name Symbol Health Damage Gold
dragon dragon D 20 4 100
orc orc o 4 2 25
slime slime s 1 1 10

Next step is to write a Monster constructor, so we can create monsters. The Monster constructor should take a Type enum as a parameter, and then create a Monster with the appropriate stats for that kind of monster.

There are a number of different ways to implement this (some better, some worse). However in this case, because all of our monster attributes are predefined (not random), we'll use a lookup table. A lookup table is an array that holds all of the predefined attributes. We can use the lookup table to look up the attributes for a given monster as needed.

So how do we implement this lookup table? It's not hard. We just need an array that contains an element for each monster Type. Each array element will contain a Creature that contains all of the predefined attribute values for that Type of Monster. We place this array inside of a static member function of Monster so that we can get a default Creature for a given Monster::Type.

The definition of the lookup table is as follows:

Now we can call this function to lookup any values we need! For example, to get a Dragon's gold, we can call getDefaultCreature(Type::dragon).getGold().

Use this function and delegating constructors to implement your Monster constructor.

The following program should compile:

and print:

A orc (o) was created.

Show Solution

e) Finally, add a static function to Monster named getRandomMonster(). This function should pick a random number from 0 to max_types-1 and return a monster (by value) with that Type (you'll need to static_cast the int to a Type to pass it to the Monster constructor).

Lesson 5.9 -- Random number generation contains code you can use to pick a random number.

The following main function should run:

The results of this program should be randomized.

Show Solution

f) We're finally set to write our game logic!

Here are the rules for the game:

The player encounters one randomly generated monster at a time.
For each monster, the player has two choices: (R)un or (F)ight.
If the player decides to Run, they have a 50% chance of escaping.
If the player escapes, they move to the next encounter with no ill effects.
If the player does not escape, the monster gets a free attack, and the player chooses their next action.
If the player chooses to fight, the player attacks first. The monster's health is reduced by the player's damage.
If the monster dies, the player takes any gold the monster is carrying. The player also levels up, increasing their level and damage by 1.
If the monster does not die, the monster attacks the player back. The player's health is reduced by the monster's damage.
The game ends when the player has died (loss) or reached level 20 (win)
If the player dies, the game should tell the player what level they were and how much gold they had.
If the player wins, the game should tell the player they won, and how much gold they had
Here's a sample game session:

Enter your name: Alex
Welcome, Alex
You have encountered a slime (s).
(R)un or (F)ight: f
You hit the slime for 1 damage.
You killed the slime.
You are now level 2.
You found 10 gold.
You have encountered a dragon (D).
(R)un or (F)ight: r
You failed to flee.
The dragon hit you for 4 damage.
(R)un or (F)ight: r
You successfully fled.
You have encountered a orc (o).
(R)un or (F)ight: f
You hit the orc for 2 damage.
The orc hit you for 2 damage.
(R)un or (F)ight: f
You hit the orc for 2 damage.
You killed the orc.
You are now level 3.
You found 25 gold.
You have encountered a dragon (D).
(R)un or (F)ight: r
You failed to flee.
The dragon hit you for 4 damage.
You died at level 3 and with 35 gold.
Too bad you can't take it with you!
Hint: Create 4 functions:

The main() function should handle game setup (creating the Player) and the main game loop.
fightMonster() handles the fight between the Player and a single Monster, including asking the player what they want to do, handling the run or fight cases.
attackMonster() handles the player attacking the monster, including leveling up.
attackPlayer() handles the monster attacking the player.

Show Solution

g) Extra credit:
Reader Tom didn't sharpen his sword enough to defeat the mighty dragon. Help him by implementing the following potions in different sizes:

Type Effect (Small) Effect (Medium) Effect (Large)
Health +2 Health +2 Health +5 Health
Strength +1 Damage +1 Damage +1 Damage
Poison -1 Health -1 Health -1 Health

Feel free to get creative and add more potions or change their effects!

The player has a 30% chance of finding a potion after every won fight and has the choice between drinking or not drinking it. If the player doesn't drink the potion, it disappears. The player doesn't know what type of potion was found until the player drinks it, at which point the type and size of the potion is revealed and the effect is applied.

In the following example, the player found a poison potion and died from drinking it (Poison was much more damaging in this example)

You have encountered a slime (s).
(R)un or (F)ight: f
You hit the slime for 1 damage.
You killed the slime.
You are now level 2.
You found 10 gold.
You found a mythical potion! Do you want to drink it? [y/n]: y
You drank a Medium potion of Poison
You died at level 2 and with 10 gold.
Too bad you can't take it with you!

Show Hint

Show Solution


12.1 -- Pointers and references to the base class of derived objects
Index
11.7 -- Multiple inheritance

392 comments to 11.x — Chapter 11 comprehensive quiz

  • Quiz Q #2 part a

    Would you please check the following for the quiz question #2 part 'a' and 'b'? And do you think it is a good idea to write in this way?

  • TimCook

    >>The protected access specifier allows the class the member belongs to, friends, and derived classes to access the protected member, but not the public.

    If we have the code below, would you please tell me how the protected access specifier allows the class the member belongs to access the protected membe?
    Thanks.

  • Glenn

    I'd be grateful for any feedback on my own implementation of the 'potions' idea at Quiz 2g. In particular, is it in any respect 'the wrong way of doing things' or 'unnecessarily complex'? (I was aiming not to have to touch any of the other Creature/Player/Monster classes.) [Edit: But I did add positive analogues to Creature::reduceHealth() for restoring health and increasing attack power.] Thanks in advance!

    'potionCheck(pc)' is then called within my 'You killed the monster' code-block.

  • yolo

    I have a question for exercise 2b. Why does the Apple constructor for GrannySmith prefers to choose the protected and not the public Apple constructor? Is it because it is the first one in order or because it CAN access it and prefers to access the contructor with the most "privacy" order(Like me prefering a private toilet and not a public just because i can)?

  • Gustaw

    So, I finished my piece of code. Writing the game wasn't easy, but it wasn't a "killer". But implementing potions was much harder for me.
    And here's my code. I would appreciate every feedback on it.

    • nascardriver

      - Functions that don't modify `this` should be `const`
      - Variables, especially reference parameters, that you don't modify should be `const`.
      - Inconsistent formatting. Use an auto-formatter.
      - Initialize with list initialization for higher type-safety
      - Initialize variables in the member initializer list rather than assigning to them
      - You have enums for potion type/size, use them. Strings are for humans and your integers are magic.
      - `getRandomTypePotion::names` should be `static` and `constexpr`. Otherwise you're creating it every time `getRandomTypePotion` gets called. `getRandomTypePotion` can them also return by const reference.
      - `getRandomSizePotion::sizes` should be `static` and `constexpr`.
      - Avoid recursion, use loops. Your program will run out of memory if you recurse too much.
      - Pass non-fundamental types by reference. Copying them is slow. Plus this is what breaks your `potionEffect()`.
      - Line 167-171: `int effect{ potion.getSize() + 1 }`
      - Line 174+: Duplicate code. Apart from the `player.xxx(effect)`, the code is unconditional.
      - Line 198: Cast has no effect
      - Line 263 should be moved into the default case of the `switch` below to avoid the duplicate comparison
      - You're seeding `std::rand` but aren't using it
      - Line 321, 326, 327: You have functions for that

      I suppose most of these points are caused by you working on this quiz for an extended period of time, causing you to switch styles and forget about things you did earlier. But there are some fundamental issues like recursion and passing by value that should be addressed. Try to fix the points I mentioned above or remember them in the next quiz. I'll happily review an updated version of your code. If you have any questions, feel free to ask :)

      • Gustaw

        First of all, thank you very much for reviewing my code. Here is updated version of it, and I hope I managed to fix (at least) most of my mistakes. Stll, I have one problem. I tried to make getRandomPotion() in line 164 static constexpr, but while it's working as static const, adding constexpr gives me an error. So my question is, what is the difference between const and constexpr? I know that we should add constexpr to our "magic intengers", but I would love to know more than that. And once again, thank you for help.

        • nascardriver

          You got most of them, some leftovers:
          - Line 13, 125 can use list initialization
          - Returning by `const` value does more bad than good.
          - Formatting is inconsistent. Your editor can very likely already format your code, you just need to press a shortcut.
          - `printSizeBecauseWhyNote` and `potionEffect` are using magic numbers/strings, use your enumerators
          - Line 333: You could `assert(false)` if you think this should never happen. If code is unreachable, don't write it.
          - `attackPlayer::monster` should be `const`

          New:
          - Line 258, 264 and 292, 307+: Duplication comparisons. These can be solved by writing a `bool getDecision(char yes, char no)` function.

          `constexpr` requires that the expression can be evaluated at compile-time, `const` doesn't. `const` only means that the object can't be modified. Everything that's `constexpr` is automatically `const`.
          `getRandomPotion()` uses a random number generator. Your program needs to be running to generate random numbers.

  • Ismael

    This quiz really helped me understand inheritance and how to design my classes. I wanted to ask though, how come you use

    for fleeing instead of just

  • srt1104

    Wouldn't it be better to return Creature by reference here:

    since we are only using it to initialize the Creature part of Monster object using copy constructor?

    Also, in getPotionTypeName() and getPotionSizeName(), would it make any difference if we make std::array names, constexpr?

    • nascardriver

      I spent 10 minutes trying to figure out why there were 2 copies taking place, then I noticed that yes, this should have been a reference all along

      This doesn't make sense, as it prevents the caller from moving (A fast shallow copy, covered later) the return value. `const` there only makes sense if we're returning a reference. I've updated the lesson, thanks for pointing it out!

      As per best practice, the `names` arrays should be `constexpr`. It doesn't make a difference in this specific case. You'd get better output if you were to use `names` in a `constexpr` context, eg.

  • beko

    hi,first of all thanks so much for tutorials - my solution for last quiz any suggest