Ch13: Classes
Overview
Everything you have written so far has been made of the types somebody else
defined: ::std::int_least32_t, ::fast_io::string,
::fast_io::str_btree_map. A class is how you
define a type yourself.
A class puts data and the functions that work on that data into one thing, gives that thing a name, and then decides what the rest of the program is allowed to do with it. That last part is the point of the whole chapter: a class is not just a bag of fields, it is a small set of promises with the implementation hidden behind them.
The chapter follows one type from a first draft to a finished design: a
point at the beginning, an account by the end. Each
subchapter adds one idea, and the code grows with it.
| You want to | Read |
|---|---|
| Put data and behaviour into one type | Ch13.1, Ch13.2 |
| Write functions that cannot accidentally change an object | Ch13.3 |
| Decide what the outside world may touch | Ch13.4, Ch13.5 |
| Control how an object comes into existence | Ch13.6 |
Understand the invisible this argument |
Ch13.7 |
| Keep one variable or one function for the whole class | Ch13.8, Ch13.9 |
| Let exactly one outsider reach the private parts | Ch13.10 |
Conventions Used in This Chapter
-
No
int. Integer types are written::std::int_least32_t(or::std::int_least64_tfor money), and sizes are::std::size_t. The width of anintis not guaranteed by the language; the width of these types is. Use the type that says what you mean, not the shortest one to type. -
Private data members end with
_(balance_), public data members do not (x). One glance tells you which side of the wall a name lives on. -
Every member function is
noexceptorthrows, exactly like a free function (Ch6.16). A member function that can fail is declaredthrows, and the caller handles it withtry { } catch throws (::std::error e) { }(Ch3.16). - Every example is a complete program and the output under it is the output you get when you run it.
Contents
- Ch13.1: What a Class Is: Data and the Functions That Belong to It
- Ch13.2: Member Functions
- Ch13.3: const Member Functions: Promising Not to Modify
- Ch13.4: Access Control: public and private
- Ch13.5: Encapsulation: Keeping the Invariant True
- Ch13.6: Constructors: How an Object Comes Into Existence
- Ch13.7: The this Pointer
- Ch13.8: Static Data Members
- Ch13.9: Static Member Functions
- Ch13.10: friend: Letting One Outsider In
- Ch13.11: Putting It Together