4.x — Chapter 4 comprehensive quiz

Quick review

We covered a lot of material in this chapter. Good job, you’re doing great!

A block of statements (aka. a compound statement) is treated by the compiler as if it were a single statement. These are placed between curly brackets ({ and }) and used pretty much everywhere.

Local variables are variables defined within a function. They are created at the point of variable definition, and destroyed when the block they are declared in is exited. They can only be accessed inside the block in which they are declared.

Global variables are variables defined outside of a function. They are created when the program starts, and are destroyed when it ends. They can be used anywhere in the program. Non-const global variables should generally be avoided because they are evil.

The static keyword can be used to give a global variable internal linkage, so it can only be used in the file in which it is declared. It can also be used to give a local variable static duration, which means the local variable retains its value, even after it goes out of scope.

Namespaces are an area in which all names are guaranteed to be unique. Use of namespace is a great way to avoid naming collisions. Avoid use of “using statements” outside of functions.

Implicit type conversion happens when one type is converted into another type without using a cast. Explicit type conversion happens when one type is converted to another using a cast. In some cases, this is totally safe, and in others, data may be lost. Avoid C-style casts and use static_cast instead.

std::string offers an easy way to deal with text strings. Strings are always placed between double quotes.

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 should be used instead of standard enums if your compiler is C++11 capable.

Typedefs allow us to create an alias for a type’s name. Fixed width integers are implemented using typedefs. Typedefs are useful for giving simple names to complicated types.

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!


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. If you’re using C++11, use an enum class for this. If you’re using an older compiler, use an enumeration 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.

C++11 solution: Show Solution

non-C++11 solution: Show Solution

5.1 -- Control flow introduction
4.8 -- The auto keyword

123 comments to 4.x — Chapter 4 comprehensive quiz

  • Chetan

    • nascardriver

      Hi Chetan!

      I've added comments to your code, feel free to ask any questions that may come up.

  • Dear nascardriver!

    is it ok if I skip this due to the lack of my understanding in enums?

    • nascardriver

      Hi Ali!

      You can skip it but you'll come across enums sooner or later.
      enums are just a bunch of named integers.

    • WiseFool

      Ali, I'm usually quick to understand things, but I struggle a bit with enumerations, too.  Your problem may be like mine: I keep looking for some "there" there that just isn't there - some great purpose and use for them.  Although they're a "cool" concept, there's so little practical use for them that you have to almost contrive ways to use them.  And you end up having to use a series of if statements or a switch statement to make use of them anyway, so why bother using them?  I've concluded that the best thing about them is that they're a good way to document in english on the spot what a coded number means.
      for example:
          if (monsterType == 0)
      bad: what does that number code 0 mean?
          if (monster.type == MonsterType::OGRE)
      much better!

      • Alex

        Personally, I use enumerations all of the time. More than many of the other concepts in C++. Why? Because they allow us to define sets of things and give them descriptive names. As you note above, MonsterType::OGRE is much more descriptive than the literal 0. Also, enums pair really well with arrays (something we discuss in chapter 6), so you can use an enumerator as an array index. For example, inventory[ItemTypes::TORCH] is much more meaningful than inventory[0].

        Pretty much anywhere you are thinking about using an integer to identify or select from a small set of well-defined objects, an enumerated value is a better choice.

  • Matt

    Here's my take on this chapter's quiz.  I found that using an enum class seemed to generate more work than it saved (though that is probably because of how I used it).  I recall the lesson on enums mentioning that they don't play nicely with std::cin but I gave it a go anyway.  What I can say is that this quiz gave me a new appreciation for all of those games I played growing up.  I can't imagine what a fully-functional game's code must look like!

    • nascardriver

      Hi Matt!

      Nice code once again, here are my two cents:

      General: Inconsistent use of '\n' and std::endl
      @spawnMonster: Don't hardcode enum ids and don't let the user input an id directly, this will cause problems when modifying the @MonsterType enumeration or when the user enters an invalid id. Using a separate function to convert string <> int <> MonsterType is better (Use a switch statement like you did in @printMonster).
      Line 28: Use std::numeric_limits<std::streamsize>::max() instead of 32767 for real applications (Doesn't matter here)
      Line 32: That's correct
      @printMonster: Imagine you want to return a string or write to a file rather than writing directly to std::cout, that's going to be a lot of work updating this function. Constructing a string containing the full sentence and writing that string to std::cout is more portable.

    • Hi  Matt!
      I pretty much understood everything from your code but what did you do in line 28?

      oh and are you just a starter? because it doesn't seem so 🙂

      • nascardriver

        std::cin.ignore ignores all characters in the input stream until the given character ('\n') is reached (inclusive).
        You don't need to understand this now, it's part of lesson 5.10.

      • Matt

        Ali Dahud,

        Thanks, I'm flattered but I am indeed a novice.  In all honesty though, I started going through this series a couple years ago and made it to lesson 3 or so before I got deployed and forgot everything.  That said, this is my second voyage through the material up to this point.  Even so, I still have to regularly refer back to previous lessons to remember how to do something, which I think is OK, not many people remember 100% of what they learn on the first exposure.  Alex and nascardriver still find things that can be improved with my code so I'm far from the example to emulate - just a fellow student like you!

        I think your questions have already been answered.  Best of luck!


  • Silviu

    In lesson 4.4b - An introduction in std::string , i would appreciate if was an example like in this quiz using a function of std::string.But great lessons to learn ! Thank you.

  • Andreas

    So basically if i understood this,its not recommended doing this :

    #include <iostream>

    using namespace std; // This is not recommended,right?

    int main() etc.

    I dont like using 'using namespace std;' myself, i prefer writing full std::cout/cin/string.
    I know its useful if std starts to repeat but only INSIDE functions,not at pure beginning of program,rigt?

    • nascardriver

      Hi Andreas!

      > its not recommended doing this

      > I know its useful if std starts to repeat but only INSIDE functions,not at pure beginning of program,rigt?
      You mean having a using directive inside a function instead of an entire file?
      It's not as bad, but it's still bad.

  • Sirius

    Hi, I have a quick question about namespaces and structs. I placed the enum code for the quiz inside the struct block so I could experiment:

    Since all

    versions have to be replaced with

    versions I wanted to implement a using directive or using declaration instead of replacing every MonsterType with Monster::MonsterType however I wasn't able to get it to work properly. I tried


    How would one go about getting namespaces to work in this situation, if it's at all possible? Thanks!

    • nascardriver

      Hi Sirius!

      Those assume that @Monster is a namespace. @Monster isn't a namespace so it doesn't work.

      What you are looking for is a type alias

      See lesson 4.6 (Typedefs and type aliases)

      • Sirius

        Thank you for the solution! Would you warn against placing enums inside structs in this manner?

        I quite like the aesthetic of grouping the variables together this way (and it does save some space) but I understand that it could be difficult to debug or understand if you're viewing the program for the first time, especially with type aliases all over the place.

        • nascardriver

          "Would you warn against placing enums inside structs in this manner?"
          I rarely use structs, classes do everything a struct does and more, so there's rarely a reason to use a struct over a class.
          You can place enums inside structs no problem but if you're planning on type aliasing the enum everywhere you might just as well place the enum outside.

          • Alex

            My opinion is if an enum is tied to the struct or class, placing the enum inside the struct or class is better than outside, as it makes it clearer that the two are bound together. Generally when I do this, I use enum instead of enum class though (since the class or struct provides a namespacing effect).

  • Aashish Bharadwaj




  • fhmadcode

    Hi Alex, can you help me explain the different between the following statements?
    Although they are both acceptable in complier, I guess type 1 is more efficient than type2 ?

    • Alex

      They should be identical -- both do aggregate initialization. #2 uses the classic style, whereas #1 uses the uniform initialization style (introduced in C++11).

  • greatTutorials(Alex);

    My code

    vs c++11 solution

    Is my solution okay, or in any way less efficient?
    Could printing the type like I did instead of returning a string be useful for something else in a program or would a string just do the same and more?


    • Alex

      If all you need to do is print the name, then having a function that just prints the name is probably more efficient than returning a string and having the caller do the print. It's just less reusable since the caller can do anything with a string, but a function that prints can only print.

      Short answer: Since you don't need the string anywhere else, your code is fine. 🙂

  • KP

    #include "stdafx.h"
    #include <iostream>
    #include <string>

    enum class MonsterType

    struct Monster
        std::string name;
        int health;
        MonsterType type;

    std::string getMonsterType(Monster monster)
        if (monster.type == MonsterType::OGRE)
            return "Ogre";
        if (monster.type == MonsterType::DRAGON)
            return "Dragon";
        if (monster.type == MonsterType::ORC)
            return "Orc";
        if (monster.type == MonsterType::SPIDER)
            return "Giant Spider";
        if (monster.type == MonsterType::SLIME)
            return "Slime";

        return "Unknown";

    void printMonster(Monster monster)
        std::cout << "This " << getMonsterType(monster) << " is named " << << " and has " << << "health\n";

    int main()
        Monster OGRE = { MonsterType::OGRE, "Trog", 145 };
        Monster SLIME = { MonsterType::SLIME, "Blurp", 24 };


        return 0;

    My code is almost identical but am getting some errors related to convert MonsterType to a std::string.
    I'm using Visual Studio 2017.

    • Alex

      The issue is that order of the members of the struct Monster don't match the order in which you're initializing your members in OGRE and SLIME. You'll need to make them consistent.

  • Kushagra

    Can you please list the programs which can be made till these topics , so that we can practice them at home .

  • codenoob


    This is what I made up. Is it a lot worse than the one in your example? 🙂
    Thanks for the site btw, it's just great and I think I'm starting to get a hang of this a bit at a time.

    • Alex

      Structurally the program looks good, you're just doing a few things that are less efficient. First, you're unnecessarily casing enumerators of type MonsterType to integers, when that's not necessary. Second, you're returning string literals as std::string when all you're doing is printing them. Returning char* would avoid an unnecessary conversion.

      • codenoob

        Thanks. Haha, yeah I actually ran into an error that I couldn't understand and get past until I used the static casts. 🙂 Now that I look at your example I see the problem was in my struct and all I tried fixing was in the getMonsterType function and the monster creation.
        But I guess realizing your own errors and how to fix them may be the hardest part. 😀

  • lnm

    I completed the quiz. Please check it or correct it :D.

    I love your tutorial since i'm rushing it. Thanks.

  • antiriad7

    Why didn't you simply do like this:

  • c++ learner

    compiler shows that MonsterType is not a class or namespace

  • Vissarion

    std::cout << "This " << type(monster) << "is named " << << "and has " << << "health";
    In this line of code, my compiler produces an error "No operator "<<" matches these operands" and it refers to the second time I use them, between "this" and type(monster), what could be wrong?
    Thanks in advance

  • I am attempting to design a program using the information learned in this chapter, basically a simple math quiz that tells you how you did at the end. Here is the code:

    I get an error on line 7 that says 'error: invalid use of non-static data member UserInformation::userName'. What does this mean and how can I fix it? Thanks again for responding to our comments and making these awesome tutorials.

    • Alex

      UserInformation is a struct (which is a type) definition. This doesn't allocate any memory, so you can't use it to store values.

      To actually use the struct, you need to instantiate a variable of that type (which does allocate memory). Then you can use that variable to store and retrieve values.

      So basically, at the top of main, add:

      UserInformation user; // allocate a variable of type UserInformation named user

      And then anywhere you have "UserInformation::", replace it with "user.".

      • Thanks! I've got it mostly figured out now, except usually when I define a new variable of type 'auto' I get this error: "error: non-static data member declared 'auto'". I'd like to fix this so that I can make the percentCorrect variable work properly. I tested my program, purposely answered just 1 question correct, yet it said I got 0% correct instead of 33%.

        Here's my code right now:

  • Alesca

    Hi Alex. Thanks for the resource. Enjoying the tutorials.

    My compiler is raising an error related to my struct definition:

    The error: " Expected member name or ';' after declaration specifiers " pointed at the first line of the code 'struct...'

    Do you have any suggestions ?

    • Alex

      Hard to say without seeing the rest of the program. Most likely, something that came before this wasn't properly terminated with a semicolon.

      • Alesca

Leave a Comment

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