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 a static 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.16 -- Timing your code

292 comments to 8.x — Chapter 8 comprehensive quiz

  • Jeff

    How do I convert class Deck into a split file (header and cpp)? All I got is this:

    Deck.h

    Deck.cpp

    Source.cpp

    I'm not able to initialize the deck.

    • Jeff

      In case you wanted to see the Card header and cpp files as well.

      Card.h

      Card.cpp

    • Variable declarations go in the header.

      • Jeff

        When I add the variable declaration into the header, my build fails. It says:

        1>------ Build started: Project: Blackjack Project Temp, Configuration: Debug Win32 ------
        1>Deck.cpp
        1>d:\visualstudio\c++\project templates (examples projects)\blackjack project temp\blackjack project temp\deck.cpp(38): error C2440: 'initializing': cannot convert from 'const _Ty' to 'Card &'
        1>        with
        1>        [
        1>            _Ty=Card
        1>        ]
        1>d:\visualstudio\c++\project templates (examples projects)\blackjack project temp\blackjack project temp\deck.cpp(38): note: Conversion loses qualifiers

        Any idea what this means?

        • The code I posted is wrong, I don't know what I did there. @m_deck is supposed to go into @Deck, not @Card.
          "Conversion loses qualifiers" sounds like you're trying to pass a const reference to a function that wants a non-const reference. Update your code (ie. move @m_deck where it belongs) and post the new error message along with the file that the error occurs in.

  • Anthony

    I added Hand, Player and Game classes, and implemented casino rules as best I can. Multiple players, splitting and re-splitting hands permitted. I know it's a lot of code, but could you cast your eye over it and give me a few hints about where I need to improve? Thanks :)
    EDIT: Apologies.. I am unable to get the code tags working - I am using

    ?

    main.cpp:

    classes.h:

    const.h

    • I didn't look at everything, these are the things I noticed:
      * Don't write definitions in header files, that's what source files are there for (Note: C++20's modules will change this, you should learn it properly anyway).
      * "classes.h" is bad. Each class should get its own header and source file.
      * classes.h:40: You have an enum for this.
      * @getCardStr: There should be no casts in this function. Enumerators can be compared to each other.
      * @Rank and @Suit don't need to be enum class, since they're encapsulated in a class. Same for @Result and @Place.
      * You're casting your enumerators all over the place, re-read the lessons about enums.
      * classes.h:120: You have a type alias for this.
      * classes.h:182: @n cannot be negative, because it's unsigned.
      * classes.h:194: --prefix.
      * classes.h:320: Only use the conditional operator if you need the result of the expressions, use a regular if otherwise.
      * classes.h:383: @str cannot be "hit". Unnecessary conditional operator.

      Auto-generated, there are some wrong and missing line numbers but I'm not going to check them:
      main.cpp
      * Line 13: Initialize your variables with brace initializers.
      * Line 10, 11: Use std::rand instead of its global-namespaced counterpart.
      * Line 10: Use std::srand instead of its global-namespaced counterpart.
      * Line 10: Use std::time instead of its global-namespaced counterpart.

      classes.h
      * Line 125, 126, 133, 134, 148, 187, 189, 215, 216, 280, 284, 285, 292, 295, 296, 300, 315, 316, 317, 318, 322, 326, 327, 331, 35, 353, 354, 355, 36, 369, 370, 378, 386, 392, 395, 398, 405, 414, 418, 422, 423, 457, 458: Initialize your variables with brace initializers.
      * Line 133, 215, 284: Bad value
      * Line 38, 125, 126, 127, 140, 148, 219, 283, 284, 285, 286, 302, 318, 320, 327, 329, 340, 347, 355, 356, 366, 370, 387, 391, 395, 398, 410, 411, 413, 423, 436, 441, 445, 447, 458, 459: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 149: Use std::rand instead of its global-namespaced counterpart.

      const.h
      * Line 10: Limit your lines to 80 characters in length for better readability on small displays.

    • Anthony

      Thank you so much for helping me. Really, really appreciated.

      Yes, I was under the mistaken impression that switch has to be used exclusively with ints, and so I was doing all that crazy casting! Ha :)

      classes.h:182: @n cannot be negative, because it's unsigned.  <-- This was because at one point I'd tried out iterating through the array backwards, and needed to guard against a negative index.

      And yes, I need to uniform initialise all my for loop variables! I'm in the habit of using copy initialisation.

      Thanks again,

      Anthony

      • > I'd tried out iterating through the array backwards, and needed to guard against a negative index
        Be careful when iterating backwards with unsigned ints.

  • Shri

    In the solution for 4b) , I'm confused about the following line of code:

    Where MAX_SUITS is defined this way:

    I don't understand this:
    1. How can we access MAX_SUITS like above, when we have not declared "enum CardSuit" as static. Shouldn't we need Card class object to access MAX_SUITS?

    As per my understanding, to access MAX_SUITS, we should have used something like this:

    Please clarify this for me.

    • Alex

      Card and Card::CardSuit are both types, and types only need a definition to be accessible (as types doesn't allocate any storage -- only objects of the type require storage).

      Consider this similar case:

      This code runs fine. We're asking the compiler to get the size of the m_x member of the C class, which it knows because it has seen the declaration of C. This doesn't require an object to be instantiated.

  • Mike

    Hi, in the 3rd question, I have used the Mersenne Twister algorithm and I don't know if I have used it correctly or not.
    I would appreciate it if someone could check it.

    another interesting thing, I was able to compile my code in CodeBlocks even though I have accidentally dropped the keyword "int" in line 75, and I have all the warnings turned on.

    Thank you for the great lessons!

    • Hi Mike!

      * Line 98: Initialize your variables with brace initializers. You used copy initialization.
      * Line 80, 90: Initialize your variables with brace initializers. You used direct initialization.
      * Line 23, 24, 25, 26: Initialize your variables with brace initializers.
      * Line 29, 62, 78, 87, 88, 90, 91: Limit your lines to 80 characters in length for better readability on small displays.
      * Inconsistent formatting. Use your editor's auto-formatting feature.
      * @getTypeString should return a const char * or an @std::string_view to prevent creating a copy of the string with every call.
      * See my comment here ( https://www.learncpp.com/cpp-tutorial/59-random-number-generation/comment-page-5/#comment-401088 ) about @std::mt19937 construction.
      * Line 91: Magic number: 5. Use @std::size(s_names) and @std::size(s_roars).

      Your usage of the mersenne twister is correct, apart from the construction, but that's not your fault.

  • Arthur

    too a while to get it working and not sure I did things right , but it works. tried some different naming styles for variables and gave descriptive names to avoid commenting, I find a lot of comments make it harder to read, curious to know if it is readable without comment.

    still have to figure out how to separate it into the different files...