Search

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 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 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!

Yay.

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
Index
4.8 -- The auto keyword

99 comments to 4.x — Chapter 4 comprehensive quiz

  • 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?

    Thanks

    • 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
    {
        OGRE,
        DRAGON,
        ORC,
        SPIDER,
        SLIME
    };

    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 " << monster.name << " and has " << monster.health << "health\n";
    }

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

        printMonster(OGRE);
        printMonster(SLIME);

        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

    Hey!

    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 " << monster.name << "and has " << monster.health << "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:

      [code]
      UserInformation user; // allocate a variable of type UserInformation named user
      [code]

      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 C++ code inside [code][/code] tags to use the syntax highlighter