Teaching Notes: Module 06
Key Learning Objectives
Section titled “Key Learning Objectives”- Four C++ cast types
- When to use each cast
- Type detection at runtime
- Serialization concepts
Exercise 00: Scalar Type Converter
Section titled “Exercise 00: Scalar Type Converter”Type Detection Order
Section titled “Type Detection Order”- Check for char (single printable char)
- Check for int (all digits, optional sign)
- Check for float (has ‘f’ suffix)
- Check for double (decimal point, no ‘f’)
- Handle special: nan, inf, nanf, inff
Common Mistakes
Section titled “Common Mistakes”-
Not handling all edge cases
- Empty string
- Just ”-” or ”+”
- Multiple decimal points
- “nan” vs “nanf”
-
Display format issues
// Float/double should show .0 for whole numbersstd::cout << std::fixed << std::setprecision(1);std::cout << 42.0f; // "42.0f" not "42f" -
Overflow detection
- int overflow -> “impossible”
- Non-displayable char -> “Non displayable”
Which Cast?
Section titled “Which Cast?”- Numeric conversions:
static_cast
Exercise 01: Serialization
Section titled “Exercise 01: Serialization”Key Concept
Section titled “Key Concept”Convert pointer to integer and back.
uintptr_t Serializer::serialize(Data* ptr) { return reinterpret_cast<uintptr_t>(ptr);}
Data* Serializer::deserialize(uintptr_t raw) { return reinterpret_cast<Data*>(raw);}Which Cast?
Section titled “Which Cast?”reinterpret_cast- bit-level reinterpretation
Common Mistakes
Section titled “Common Mistakes”-
Empty Data struct
- Subject requires non-empty Data
-
Not testing round-trip
Data d;uintptr_t raw = Serializer::serialize(&d);Data* result = Serializer::deserialize(raw);assert(result == &d); // Must be same address!
Exercise 02: Type Identification
Section titled “Exercise 02: Type Identification”Without typeinfo
Section titled “Without typeinfo”Must use dynamic_cast to identify types.
Pointer Version (returns NULL on failure)
Section titled “Pointer Version (returns NULL on failure)”void identify(Base* p) { if (dynamic_cast<A*>(p)) std::cout << "A" << std::endl; else if (dynamic_cast<B*>(p)) std::cout << "B" << std::endl; else if (dynamic_cast<C*>(p)) std::cout << "C" << std::endl;}Reference Version (throws on failure)
Section titled “Reference Version (throws on failure)”void identify(Base& p) { try { (void)dynamic_cast<A&>(p); std::cout << "A" << std::endl; return; } catch (...) {} // Try B, C...}Common Mistakes
Section titled “Common Mistakes”-
Using typeid (forbidden)
<typeinfo>header is forbidden
-
Pointer inside reference version
- Subject forbids using pointer in reference version
-
Base must be polymorphic
- Need at least one virtual function (virtual destructor counts)
Which Cast?
Section titled “Which Cast?”dynamic_cast- runtime type identification