9.x — Chapter 9 summary and quiz

Quick review

Enumerated types let us define our own type where all of the possible values are enumerated. These are great for categorizing things.

Enum classes work like enums but offer more type safety and don’t pollute the encapsulating namespace quite as much.

And finally, structs offer us a way to group related variables into a single structure and access them using the member selection operator (.). Object-oriented programming builds heavily on top of these, so if you learn one thing from this chapter, make sure it’s this one.

Quiz time


Question #1

In designing a game, we decide we want to have monsters, because everyone likes fighting monsters. Declare a struct that represents your monster. The monster should have a type that can be one of the following: an ogre, a dragon, an orc, a giant spider, or a slime. Use an enum class for this.

Each individual monster should also have a name (use a std::string), as well as an amount of health that represents how much damage they can take before they die. Write a function named printMonster() that prints out all of the struct’s members. Instantiate an ogre and a slime, initialize them using an initializer list, and pass them to printMonster().

Your program should produce the following output:

This Ogre is named Torg and has 145 health.
This Slime is named Blurp and has 23 health.

Show Solution

10.1 -- Arrays (Part I)
9.5 -- Random number generation

92 comments to 9.x — Chapter 9 summary and quiz

  • Anthony Demin Liu

    I like this solution.

  • Aasif Ali

    can anyone clear my doubt..

    void printMonster(Monster monster)
        std::cout << "This " << getMonsterTypeString(monster.type) <<
            " is named " << <<
            " and has " << << " health.\n";
    In this funtion we used (Monster monster) variable but we did not declare monster in int main or anywhere. plzz help me its really confusing

  • Lots of debugging on this one getting namespaces and scopes correct and properly understood!  Need to focus on better a better naming strategy and commenting my code!

  • Armando IG

    Hello, this is my code for the quiz, is there any feedback? Also I saw you made a separate function to get the monster type, is that better than what I did when including it into print monster?

    Thanks in advance!

    • nascardriver

      The benefit to having a separate function to get the monster type name is that you can use the name for anything else. For example, if you want to render monsters on the screen with their name, you have no way of getting their name.

  • fqwef q

    I thought switch statement only works with intergers. And enumclass doesnt auto convert to int?

    • Alex

      Switch statements work with both integral and enumerated types (including enum and enum class). I amended the lesson on switch statements to explicitly note this. Thanks for pointing this out!

  • James C

    Should you be using the {} in the quiz struct definition? I know it doesn't make a difference if you make sure to initialize a new struct variable with {}, but if you don't, you get garbage values (at least in VS).

  • James C

    Damn, I got almost 1:1 with the quiz question, apart from a couple identifier choices! (I didn't cheat, I promise!)

  • Ahmed

    are there any bad practices in my code?

    • James C

      You are repeating 'monster' in the names of the MonsterInfo variables, and also the MonsterType enumerators. is obviously the monster's name, you don't need monster.monsterName. Also for the enumerators, MonsterType::ogre is very readable, and also takes less typing than MonsterType::monster_ogre.

      Remember, you don't need to prefix the enumerators if you're using 'enum class', because it forces you to prefix the enum name followed by :: (like MonsterType::), whereas with the standard enum, you don't need to prefix the enum name, so for that you should probably use a prefix like monster_ for each value. But you should prefer enum classes over enums anyway.

  • Ladyoftheroundtable

    Everyone else throws up their code on these quizzes, so why not. I did combine the print and monster type to string functions, which definitely falls outside of the parameter of asking a function to do only one thing, I didn't think of that at the time. It just felt like part of the process of printing. Also, monst1 is declared outside of list initialization because I forgot that parameter, but I did it right for monst2. I'm also unhappy with the type names and the variable names being so similar. The official solution is similar in this regard, but it feels ambiguous and hard to read. Also, I forgot to safe guard this code, but given that it takes no user inputs it's probably fine this once.

    • nascardriver

      This is dangerous, you're accessing `monst2` before it has been fully initialized. It's only legal because `monst` is initialized before `health`. If you swapped the two members, ie.

      That'd be undefined behavior.

      If your member initializations depend on each other, write a function that initializes them in a safe order, for example

      You'll later learn how to do this without a separate function (Class Constructors).

      On the same line, you're getting a compiler warning. Make sure your compiler is configured properly and fix warnings.

      If you add a function that converts a `Monster_type` to `std::string`, you'll not only have fewer code (Because you don't need `break`), but also do less in each function.

  • Josh

    Hi, just a heads up. You might want to move the part about std::string to chapter 4 as it's no longer in this chapter

  • Rayyan Khan

    Super Happy with my solution ( I haven't checked the official one yet, but it has got to be similar!)

  • Jay R

    It took me a while to figure out why my program wouldn't allow me to use enum class. I used a reminder from chapter 9 to do a static cast. I know, it's not the easiest to read and I should have created a separate function for getting the monster type, but here goes nothing. Lol..

    Thank you Nascar and Alex :)

    • nascardriver

      When you add a monster to your enum, what happens?

      • Jay R

        This ogre is named Torg and has 145 health.
        Unknown monster type.
        Program ended with exit code: 0

        It makes my program behave in an unexpected way. I expected it to output the information for Blurp, but since slime is not included in my switch case the default case is executed.

        • nascardriver

          The problem isn't that you're not handling a slime, you have a case for slimes, but you've used magic numbers. You should only get "Unknown monster type" if you try to print a `snake`.
          Don't cast `m.monster_type` to an `int`, switch `m.monster_type` directly and use enumerators for the case labels.

          • Jay R

            Okay, I think I understand.. I added scope qualifiers to the case labels since I'm using an enum class. I hope this it what you mean. Here is the fixed code:

  • Medhat Diab

Leave a Comment

Put all code inside code tags: [code]your code here[/code]