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