Download presentation
Presentation is loading. Please wait.
Published byConstance Nelson Modified over 9 years ago
1
Abstract Classes & Object Slicing
2
Pure Virtual Functions Virtual Function : Child class may override, if working with pointer/reference, check to see if we have a better version
3
Pure Virtual Functions Pure Virtual Function : Child class MUST override this… I'm not even going to describe how it works
4
New Problem… Can't make a GeometricObject:
5
Abstract Abstract Class : Class that is not designed to be instantiated – Defines common capabilities for subclasses GeometricObject +getArea() : double +getPerimeter() : double Italics = Abstract Class Italics = Abstract Method (Pure Virtual)
6
A Promise Abstract class is an organizer / promise
7
Using it We have no idea how each object will get its area, but we know it can:
8
Constructors Can't make a Geo object: Still need constructors for child classes
9
Protected Constructors Protected constructors make sure only usable from inside child classes GeometricObject +getArea() : double +getPerimeter() : double # = Protected
10
Object Slicing Assigning subtype to parent type variable slices the object Geometric Object Rectangle r1
11
Object Slicing Assigning subtype to parent type variable slices the object Geometric Object Rectangle r1 Geometric Object r2
12
Pointers/References Pointers / References don't slice – Just store memory address, don't have to
13
Casting No cast required to store child address in parent ptr: Virtual dispatch still finds child version of functions
14
Down Casting Can't auto convert parent pointer back to child one:
15
BAD static_cast, BAD static_cast happily pretends to turn a pointer into another pointer type… …weird stuff may happen
16
Static vs Dynamic Static : done at compile time Can this possibly make sense? Dynamic : done at runtime Try to see if this works…
17
Dynamic Cast dynamic_cast ( value ) – Type must be a pointer or reference – At runtime: Check to see if conversion makes sense If so, do it If not, return nullptr
18
dynamic_cast allows us to check if cast worked: GOOD dynamic_cast
19
dynamic_cast allows us to check if cast worked – Up to you to check! GOOD dynamic_cast
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.