10.x — Chapter 10 summary and quiz
Quick review#
enum classgives names to a fixed set of options.- A
structgroups values into one type. Use.to reach members. - A
classholds data and functions. An object is one made from it. public= anyone can use.private= only the class itself.- A constructor sets up a new object. Use the member initializer list.
- Mark read-only member functions
const.
Pick an answer. You find out right away if it is right.
What is an object?
The class is the blueprint. An object is one actual thing built from it.
Who can use private members of a class?
That's the point of private: the class guards its own data.
When does a constructor run?
The constructor sets up each new object as soon as it's made.
Make an enum class called Direction with the options up, down, left and right.
enum class Direction{ up, down, left, right,};Make a struct Point with two double members, x and y. Then write a function that takes two points and returns the distance between them. (Distance = square root of (dx² + dy²).)
#include <cmath> struct Point{ double x {}; double y {};}; double distance(const Point& a, const Point& b){ double dx { b.x - a.x }; double dy { b.y - a.y }; return std::sqrt(dx * dx + dy * dy);}Write a class Timer with a private int for seconds, a constructor that takes the starting seconds, a tick() function that takes away one second (but never below zero), and a bool isDone() const.
class Timer{public: Timer(int seconds) : m_seconds { seconds } { } void tick() { if (m_seconds > 0) --m_seconds; } bool isDone() const { return m_seconds == 0; } private: int m_seconds {};};Tip: press ← / → to move between lessons, / to search.