Upload
constance-nelson
View
229
Download
0
Embed Size (px)
DESCRIPTION
Pure Virtual Functions Pure Virtual Function : Child class MUST override this… I'm not even going to describe how it works
Citation preview
Abstract Classes & Object Slicing
Pure Virtual Functions
• Virtual Function : Child class may override, if working with pointer/reference, check to see if we have a better version
Pure Virtual Functions
• Pure Virtual Function : Child class MUST override this… I'm not even going to describe how it works
New Problem…
• Can't make a GeometricObject:
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)
A Promise
• Abstract class is an organizer / promise
Using it
• We have no idea how each object will get its area, but we know it can:
Constructors
• Can't make a Geo object:
• Still need constructors for child classes
Protected Constructors
• Protected constructorsmake sure only usablefrom inside child classes
GeometricObject
+getArea() : double+getPerimeter() : double
# = Protected
Object Slicing
• Assigning subtype to parent type variable slices the object
GeometricObject
Rectangle
r1
Object Slicing
• Assigning subtype to parent type variable slices the object
GeometricObject
Rectangle
r1GeometricObject
r2
Pointers/References
• Pointers / References don't slice– Just store memory address,
don't have to
Casting
• No cast required to store child address in parent ptr:
• Virtual dispatch still findschild version of functions
Down Casting
• Can't auto convert parent pointer back to child one:
BAD static_cast, BAD
• static_cast happily pretends to turn a pointer into another pointer type…
…weird stuff may happen
Static vs Dynamic
• Static : done at compile timeCan this possibly make sense?
• Dynamic : done at runtimeTry to see if this works…
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 it• If not, return nullptr
• dynamic_cast allows us to check if cast worked:
GOOD dynamic_cast
• dynamic_cast allows us to check if cast worked– Up to you to check!
GOOD dynamic_cast