Download presentation
Presentation is loading. Please wait.
1
Object Slicing & Dynamic Casts
2
Object Slicing Assigning subtype to parent type variable slices the object r1 Geometric Object Rectangle
3
Object Slicing Assigning subtype to parent type variable slices the object r1 r2 Geometric Object Rectangle Geometric Object
4
Pointers/References Pointers / References don't slice
Just store memory address, don't have to
5
Casting No cast required to store child address in parent ptr:
Virtual dispatch still finds child version of functions
6
Down Casting Can't auto convert parent pointer back to child one:
7
BAD static_cast, BAD static_cast happily pretends to turn a pointer into another pointer type… …weird stuff may happen
8
Static vs Dynamic Static : done at compile time Can this possibly make sense? Dynamic : done at runtime Try to see if this works…
9
Dynamic Cast dynamic_cast<Type>( value )
Type must be a pointer or reference At runtime: Check to see if conversion makes sense If so, do return pointer of Type If not, return nullptr
10
GOOD dynamic_cast dynamic_cast allows us to check if cast worked:
11
GOOD dynamic_cast dynamic_cast allows us to check if cast worked:
Up to you to check!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.