Search

8.x — Chapter 8 comprehensive quiz

In this chapter, we explored the meat of C++ -- object-oriented programming! This is the most important chapter in the tutorial series.

Chapter summary

Classes allow you to create your own data types that bundle both data and functions that work on that data. Data and functions inside the class are called members. Members of the class are selected by using the . operator (or -> if you’re accessing the member through a pointer).

Access specifiers allow you to specify who can access the members of a class. Public members can be accessed directly by anybody. Private members can only be accessed by other members of the class. We’ll cover protected members later, when we get to inheritance. By default, all members of a class are private and all members of a struct are public.

Encapsulation is the process of making all of your member data private, so it can not be accessed directly. This helps protect your class from misuse.

Constructors are a special type of member function that allow you to initialize objects of your class. A constructor that takes no parameters (or has all default parameters) is called a default constructor. The default constructor is used if no initialization values are provided by the user. You should always provide at least one constructor for your classes.

Member initializer lists allows you to initialize your member variables from within a constructor (rather than assigning the member variables values).

In C++11, non-static member initialization allows you to directly specify default values for member variables when they are declared.

Prior to C++11, constructors should not call other constructors (it will compile, but will not work as you expect). In C++11, constructors are allowed to call other constructors (called delegating constructors, or constructor chaining).

Destructors are another type of special member function that allow your class to clean up after itself. Any kind of deallocation or shutdown routines should be executed from here.

All member functions have a hidden *this pointer that points at the class object being modified. Most of the time you will not need to access this pointer directly. But you can if you need to.

It is good programming style to put your class definitions in a header file of the same name as the class, and define your class functions in a .cpp file of the same name as the class. This also helps avoid circular dependencies.

Member functions can (and should) be made const if they do not modify the state of the class. Const class objects can only call const member functions.

Static member variables are shared among all objects of the class. Although they can be accessed from a class object, they can also be accessed directly via the scope resolution operator.

Similarly, static member functions are member functions that have no *this pointer. They can only access static member variables.

Friend functions are functions that are treated like member functions of the class (and thus can access a class’s private data directly). Friend classes are classes where all members of the class are considered friend functions.

It’s possible to create anonymous class objects for the purpose of evaluation in an expression, or passing or returning a value.

You can also nest types within a class. This is often used with enums related to the class, but can be done with other types (including other classes) if desired.

Quiz time

1a) Write a class named Point2d. Point2d should contain two member variables of type double: m_x, and m_y, both defaulted to 0.0. Provide a constructor and a print function.

The following program should run:

This should print:

Point2d(0, 0);
Point2d(3, 4);

Show Solution

1b) Now add a member function named distanceTo that takes another Point2d as a parameter, and calculates the distance between them. Given two points (x1, y1) and (x2, y2), the distance between them can be calculated as sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)). The sqrt function lives in header cmath.

The following program should run:

This should print:

Point2d(0, 0);
Point2d(3, 4);
Distance between two points: 5

Show Solution

1c) Change function distanceTo from a member function to a non-member friend function that takes two Points as parameters. Also rename it “distanceFrom”.

The following program should run:

This should print:

Point2d(0, 0);
Point2d(3, 4);
Distance between two points: 5

Show Solution

2) Write a destructor for this class:

Show Solution

3) Let’s create a random monster generator. This one should be fun.

3a) First, let’s create an enumeration of monster types named MonsterType. Include the following monster types: Dragon, Goblin, Ogre, Orc, Skeleton, Troll, Vampire, and Zombie. Add an additional MAX_MONSTER_TYPES enum so we can count how many enumerators there are.

Show Solution

3b) Now, let’s create our Monster class. Our Monster will have 4 attributes (member variables): a type (MonsterType), a name (std::string), a roar (std::string), and the number of hit points (int). Create a Monster class that has these 4 member variables.

Show Solution

3c) enum MonsterType is specific to Monster, so move the enum inside the class as a public declaration.

Show Solution

3d) Create a constructor that allows you to initialize all of the member variables.

The following program should compile:

Show Solution

3e) Now we want to be able to print our monster so we can validate it’s correct. To do that, we’re going to need to write a function that converts a MonsterType into a std::string. Write that function (called getTypeString()), as well as a print() member function.

The following program should compile:

and print:

Bones the skeleton has 4 hit points and says *rattle*

Show Solution

3f) Now we can create a random monster generator. Let’s consider how our MonsterGenerator class will work. Ideally, we’ll ask it to give us a Monster, and it will create a random one for us. We don’t need more than one MonsterGenerator. This is a good candidate for a static class (one in which all functions are static). Create an empty MonsterGenerator class. Create a static function named generateMonster(). This should return a Monster. For now, make it return anonymous Monster(Monster::Skeleton, “Bones”, “*rattle*”, 4);

The following program should compile:

and print:

Bones the skeleton has 4 hit points and says *rattle*

Show Solution

3g) Now, MonsterGenerator needs to generate some random attributes. To do that, we’ll need to make use of this handy function:

However, because MonsterGenerator relies directly on this function, let’s put it inside the class, as a static function.

Show Solution

3h) Now edit function generateMonster() to generate a random MonsterType (between 0 and Monster::MAX_MONSTER_TYPES-1) and a random hit points (between 1 and 100). This should be fairly straightforward. Once you’ve done that, define two static fixed arrays of size 6 inside the function (named s_names and s_roars) and initialize them with 6 names and 6 sounds of your choice. Pick a random name from these arrays.

The following program should compile:

Show Solution

3i) Why did we declare variables s_names and s_roars as static?

Show Solution

4) Okay, time for that game face again. This one is going to be a challenge. Let’s rewrite the Blackjack games we wrote in chapter 6 using classes! Here’s the full code without classes:

Holy moly! Where do we even begin? Don’t worry, we can do this, but we’ll need a strategy here. This Blackjack program is really composed of four parts: the logic that deals with cards, the logic that deals with the deck of cards, the logic that deals with dealing cards from the deck, and the game logic. Our strategy will be to work on each of these pieces individually, testing each part with a small test program as we go. That way, instead of trying to convert the entire program in one go, we can do it in 4 testable parts.

Start by copying the original program into your IDE, and then commenting out everything except the #include lines.

4a) Let’s start by making Card a class instead of a struct. The good news is that the Card class is pretty similar to the Monster class from the previous quiz question. First, move the enums for CardSuit, CardRank inside the card class as public definitions (they’re intrinsically related to Card, so it makes more sense for them to be inside the class, not outside). Second, create private members to hold the CardRank and CardSuit (name them m_rank and m_suit accordingly). Third, create a public constructor for the Card class so we can initialize Cards. Forth, make sure to assign default values to the parameters so this can be used as a default constructor (pick any values you like). Finally, move the printCard() and getCardValue() functions inside the class as public members (remember to make them const!).

Important note: When using a std::array (or std::vector) where the elements are a class type, your element’s class must have a default constructor so the elements can be initialized to a reasonable default state. If you do not provide one, you’ll get a cryptic error about attempting to reference a deleted function.

The following test program should compile:

Show Solution

4b) Okay, now let’s work on a Deck class. The deck needs to hold 52 cards, so use a private std::array member to create a fixed array of 52 cards named m_deck. Second, create a constructor that takes no parameters and initializes m_deck with one of each card (modify the code from the original main() function). Inside the initialization loop, create an anonymous Card object and assign it to your deck element. Third, move printDeck into the Deck class as a public member. Fourth, move getRandomNumber() and swapCard() into the Deck class as a private static members (they’re just helper functions, so they don’t need access to *this). Fifth, move shuffleDeck into the class as a public member.

Hint: The trickiest part of this step is initializing the deck using the modified code from the original main() function. The following line shows how to do that.

The following test program should compile:

Show Solution

4c) Now we need a way to keep track of which card is next to be dealt (in the original program, this is what cardptr was for). First, add a int member named m_cardIndex and initialize it to 0. Create a public member function named dealCard(), which should return a const reference to the current card and advance the index. shuffleDeck() should also be updated to reset m_cardIndex (since if you shuffle the deck, you’ll start dealing from the top of the deck again).

The following test program should compile:

Show Solution

4d) Almost there! Now, just fix up the remaining program to use the classes you wrote above. Since most of the initialization routines has been moved into the classes, you can jettison them.

Show Solution

9.1 -- Introduction to operator overloading
Index
8.15 -- Nested types in classes

171 comments to 8.x — Chapter 8 comprehensive quiz

  • AMG

    Hey Alex,
    1. Disagree with

    I think casting is not required here, because type of arguments is the same as in constructor; so it should be

    2. getCardValue() and printCard() were declared constant, to execute const dealCard, and dealCard is constant, because pass by ref. Is it a right practice to use "const" for a "primitive" class Card inside of other class Deck? Sorry, if my question is not clear.
    Thank you for your time.

    • Alex

      1) You’re still doing a cast, you’re just using a C-style cast instead of a C++-style cast.
      2) dealCard isn’t const, it just returns a const reference (it can’t be, since it modifies m_cardIndex). If you’re asking why we return by const reference instead of by non-const reference -- you could if you wanted the user of dealCard() to be able to modify the cards. I took the position that once the deck was shuffled the cards shouldn’t be modifiable.

      • AMG

        Alex,
        Thank you very much for your answers. I still don’t understand WHY type casting is required. Here is the constructor:

        Here how I call constructor:

        Arguments are exact the same type as in constructor definition. I’m asking myself:"Why casting is needed?". Seems I’m the only one who does not get it. Alex, sorry, but cannot pass by.

        • Alex

          Type casting occurs whenever you convert a value from one type to another. Sometimes this can happen implicitly, and sometimes it must occur explicitly.

          In this case, the Card constructor expects a CardRank and CardSuit parameter, right? But in our loop, rank and suit are integers. Therefore, to use the Card constructor, we must convert our integer arguments into a CardRank and CardSuit argument. That requires type casting. So in this case, we’re being explicit about it. When we say static_cast(rank) or Card::CardRank(rank), we’re converting integer rank into a CardRank enum value, so it can be passed to the constructor.

  • AMG

    Hey Alex,
    About your answer for 1c).

    Why not

    Thank you very much.

  • AMG

    Hey Alex,
    1a) answer has extra " ".

    Should be

  • Mor

    It appears the c++14 version for quiz 2 doesn’t work with gcc, give the following error message:

    The version:  

    Tried using the following -std flags: c++14, c++1y, c++1z, c++17, gnu++14, gnu++17.  
    Using -fpermissive compiles with a warning, and the result is that the code prints nothing.

    Is it perhaps that Visual Studio is doing it’s own thing there? (it works in visual studio)

    • Alex

      Hmmm, cppreference.com seemed to indicate it would work for all compilers, but it appears not. I’ve updated the example (and lession 6.9a) accordingly. It’s very weird to me that C++ supports this for non-dynamic char arrays but not for dynamic char arrays.

      Thanks for pointing this out.

  • Jeremiah

    Ctrl + F "// Deal the player one card"
    I believe this is meant to read "// The dealer gets/shows one card" or similar.

    Also, in my solution I made printDeck() a const member function and you chose not to make it const. I know it’s unlikely that there would be const deck object but am I wrong for doing it this way?

    Thanks in advance.

    • Alex

      Thanks for pointing out the erroneous comment. It’s been fixed.

      Yes, printDeck() should probably be const, since it doesn’t modify the Deck!

  • Maleficus

    Hey Alex,
    in 1b) you write

    Wouldn’t it be better to use

    ?

    By the way thank you for this awesome tutorial!

  • KG

    While working through the quiz, I copied and pasted the HelloWorld class from question 2 into my IDE to save myself some typing and it complained about characters being outside of literals and identifiers. It stumped me for a few minutes until I took a closer look and realized that in this snippet:

    The single quotes were rendered as smart(curly) quotes, which weren’t automatically changed back to regular single quotes when I pasted it into my IDE. Find + replace made it a quick fix, but it might not be immediately obvious to everyone who does the same thing. I don’t know of a html/css fix for this off the top of my head, and searching google has surprisingly turned up nothing useful. I’m using Chrome on Mac OS X, I can’t say if it’s the same in another system/browser right now; it might not even be worth the effort for you to fix it for every possible system/browser configuration, but perhaps a little note to make people aware of it would suffice?

    Relatedly, when writing the destructor for that question, do you need to set m_data = nullptr? If not, how do you decide when that step is necessary or not?

    Thanks again.

    • Alex

      Oops, not sure how the pretty printing quotes happened. I’ve updated the lesson and replaced them with normal quotes.

      You should always set your pointers to nullptr after they are deleted unless they are going out of scope (and get destroyed) immediately after anyway.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter