From d7054beee3410b6a1f06b9938e863ee956d1f81f Mon Sep 17 00:00:00 2001 From: eggy Date: Thu, 17 Nov 2022 22:28:09 -0500 Subject: [PATCH] ece150: add exceptions and classes 2 --- docs/ce1/ece150.md | 69 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index 3120ebd..5d35c3d 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -488,3 +488,72 @@ Namespaces can also be nested within namespaces. `std::cout` does weird shenanigans that passes itself to every function afterward, such as `std::endl`. This means that `std::cout << std::endl;` is equivalent to `std::endl(std::cout);`. + +### Operator overloading + +Operators can be overloaded for various classes. + +!!! example + Overloading for displaying to `cout`: + + ```cpp + std::ostream operator<<(std::ostream &out, ClassName const &p) { + out << "text here"; + return out; + } + + +### Constructors + +Constructors can be defined with default values after a colon and before the function body: + +```cpp +Rational::Rational(): + numer_{0}, + denom_{0} { +} +``` + +Subsequent members can even use the values of previous ones. + +Constructors can also contain parameters with default values, but default values must also be present in the class declaration. + +### Member functions + +A `const` after a member function forbids the modification of any member variables within that function. + +```cpp +int get_val() const { +} +``` + +## Exceptions + +`#define NDEBUG` turns off assertions. + +`static_cast(var)` performs the typical implicit conversion explicitly during compile time. + +Exceptions are expensive error handlers that **do not protect** from program termination (e.g., attempt to access invalid memory). + +The following are all exception classes in `std`: + +- `domain_error` +- `runtime_error` +- `range_error` +- `overflow_error` +- `underflow_error` +- `logic_error` +- `length_error` +- `out_of_range` + +`...` is a catch-all exception. + +!!! example + ```cpp + try { + throw std::domain_error{"cannot compute stupidity"}; + } catch (std::domain_error &e) { + std::cerr << e->what(); + } catch (...) { + } + ```