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.

Quick 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

Question #1


a) 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

b) 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 std::sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)). The std::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

c) 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

Question #2


Write a destructor for this class:

Show Solution

Question #3


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

a) 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

b) 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

c) enum MonsterType is specific to Monster, so move the enum inside the class as a public declaration. When the enum is inside the class the “Monster” in “MonsterType” is redundant, it can be removed.

Show Solution

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

The following program should compile:

Show Solution

e) 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 Monster::Type into a 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

f) 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

g) 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

h) Now edit function generateMonster() to generate a random Monster::Type (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

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

Show Solution

Question #4


Okay, time for that game face again. This one is going to be a challenge. Let’s rewrite the Blackjack game 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.

a) 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, create private members to hold the rank and suit (name them m_rank and m_suit accordingly). Second, create a public constructor for the Card class so we can initialize Cards. Third, make the class default constructible, either by adding a default constructor or by adding default arguments to the current constructor. Finally, move the printCard() and getCardValue() functions inside the class as public members (remember to make them const!).

A reminder

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

b) 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 createDeck() function). Third, move printDeck into the Deck class as a public member. Fourth, move shuffleDeck into the class as a public member.

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

Show Hint

The following test program should compile:

Show Solution

c) Now we need a way to keep track of which card is next to be dealt (in the original program, this is what nextCardIndex was for). First, add a member named m_cardIndex to Deck and initialize it to 0. Create a public member function named dealCard(), which should return a const reference to the current card and advance m_cardIndex to the next index. shuffle() 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

d) Next up is the Player. Because playerTurn and dealerTurn are very different from each other, we’ll keep them as non-member functions. Make Player a class and add a drawCard member function that deals the player one card from the deck, increasing the player’s score. We’ll also need a member function to access the Player‘s score. For convenience, add a member function named isBust() that returns true if the player’s score exceeds the maximum (maximumScore). The following code should compile:

Show Solution

e) Almost there! Now, just fix up the remaining program to use the classes you wrote above. Since most of the functions have been moved into the classes, you can jettison them.

Show Solution


9.1 -- Introduction to operator overloading
Index
8.16 -- Timing your code

371 comments to 8.x — Chapter 8 comprehensive quiz

  • Dong

    - In h of question #2, I have a trouble because I want to use enum class instead of enum, as follows:

    And change in:

    However, I got an |76|error: no match for 'operator-' (operand types are 'Monster::Type' and 'int'). I do not know why and try to solve this problem. But I can not do that. Can you have me some advises to deal with it. Thanks.

    • nascardriver

      You can subtract from an enumerator of an `enum class`. Add another `static_cast` around the enumerator.

      • Dong

        Thank for you advises. Can you explain by code clearly?
        First, I understand this comment by subtract class in enum class. Particularly:

        Second, Add another `static_cast` around the enumerator. I do not understand? I try to put static_cast in this code but it always takes wrong message.

        • nascardriver

  • Sam

    Monster Generator

    • nascardriver

      Looks pretty good :)

      Two suggestions:
      - Initialize variables with brace initializers (Line 27).
      - Avoid abbreviations. "t", "n", "r", "h" are useless names, they make your code hard to read.

  • Hector

    How can we call from the main() the function playBlackjack() if we put it in another file?
    main.cpp

    game.cpp

    Gives a error in the linker for duplicate symbols between main.cpp and game.cpp in all methods appearing in game.cpp

  • Hector

    Your solution for 3d does not work in my project as it considers the arguments  "Bones", "*rattle*" as const char [] while the members of the class Monster are expecting std::string &.

    The complete error is:

    /Users/hectoresteban/CLionProjects/untitled/learn.cpp:6:13: error: no matching constructor for initialization of 'Monster'
        Monster skeleton{ Monster::SKELETON, "Bones", "*rattle*", 4 };
                ^       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/hectoresteban/CLionProjects/untitled/Monster.h:32:5: note: candidate constructor not viable: no known conversion from 'const char [9]' to 'std::string &' (aka 'basic_string<char, char_traits<char>, allocator<char> > &') for 3rd argument
        Monster(Type type, const std::string &name, std::string &roar, int hits):

  • mansbota

    Hello, in the Monster quiz when getting the random name and roar, shouldn't it be getRandomNumber(0, names.size() - 1), because if it returns the actual size it will be out of bounds?

    Also, wouldn't it make more sense to have the getRandomNumber function private, since we won't be using the class to just generate random numbers.

    Great tutorial btw, really enjoying it

    • Alex

      > shouldn't it be getRandomNumber(0, names.size() - 1)

      Yes, fixed.

      > Also, wouldn't it make more sense to have the getRandomNumber function private

      Yeah, probably, though it doesn't hurt in this case since the function doesn't have any side effects...

  • kavin

    Hi, is it best practice to put 'enum' inside class and 'enum class' outside the class in global namespace? Also in these quizzes you have guided us where to use a separate class , where to use a member function and where to declare a non-member function etc., I am not able to figure this out by myself. Is there any rule/way to find this out myself ? And will nested classes be of any need in OOP ?

    • nascardriver

      > is it best practice to put 'enum' inside class and 'enum class' outside the class in global namespace?
      An `enum` outside of a `class` should be used if you're using the enumerators as indexes or otherwise use their values as integers.
      `enum class` is used to prevent the enumerators from preventing the global namespace. By wrapping an `enum` inside a `class`, you're achieving the same, so there's no need to use an `enum class` inside a `class` (Though, it can be helpful when you have multiple nested enums). Nested enums cannot be forward declared. When you want to nest an enum inside of a class, think about if you're ever going to need the enum without the class (This happens in multi-file projects).

      > Is there any rule/way to find this out myself ?
      You'll figure it out as you go.

      > will nested classes be of any need in OOP ?
      No, you can do without them. They can be helpful, but it's rare. Most of the time you'll not want to nest classes.

  • Mn3m

    3H)

  • Mn3m

    1E)
    In this question I read "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.".
    So I thought getTypeString() was to be a normal free function since you mentioned "member function" with print() only... This caused me some trouble with when passing my argument to getTypeString() since it's not within the class. Therefore, I had to adjust by passing  the "this" pointer and making that free function a friend of the class. I think it was better to provide a getter instead of befriending them :p (safer). So.... Is the following acceptable or should I re-implement it?

    • nascardriver

      `getTypeString` shouldn't take a pointer. A pointer means that the argument can be a `nullptr`, but that will cause your program to crash. Use a reference instead. A reference can't be null.

  • Mn3m

    1b)

    Point2d.h

    Point2d.cpp

    • Mn3m

      1C)

      main

  • Ged

    Question number 1

    Why are using static here? I tried to run the code with and without it and can't see any difference.

    Question number 2

    What is the difference between ( 1.0 / (RAND_MAX + 1.0) )  and ( 1.0 / RAND_MAX )? Forgot it and just wanna make things clear.

    Question number 3

    When we were writing our monster code. I used std::array. Tried to use const, but it wouldn't work. So I wrote it like this. Any tips of how to improve it?