Lecture 15
Consider the following: When is a book heavy?
ordinary books: >200 pages
textbooks: >500 pages
comicbooks: >30 pages
**It returns false since Book::isHeavy() runs
Why does Book::isHeavy()
run?
Tries to fit a comic object in b while there's only space for a Book object
Comic is sliced (i.e. the hero field is chopped off)
The Comic is a Book now!
When accessing objects through pointers, slicing is unnecessary (so it won't happen)
How does compiler decide which method to run?
Uses the type of the pointer or reference to decide which isHeavy to run. (it does not consider the type of the actual object)
So a comic is only a comic if you point to it by a comic pointer or reference
How can we make Comic act like a comic even when pointed to by a Book pointer?
Solution: Declare the method virtual!
Virtual Methods/Dynamic Dispatch
Dynamic Dispatch:
Type of the object is considered at runtime, rather than from the type of the variable i.e. Choose which class method to run based on the actual type of the object at run time
To get dynamic dispatch, you need virtual methods
Polymorphism
Accomodating multiple types under one abstraction
Dynamic dispatch allows us to do this
Example of polymorphic code:
Remark: This is why we can pass an ifstream to a function
ifstream is a subclass of istream
DANGER:
The Point: Never use an array of objects polymorphically
Destructors (Polymorphism)
What happens when an object is destroyed?
Destructor body runs
Fields are destructed in reverse dealing order
Superclass part is destructed (it's destructor called)
space is deallocated
Consider:
** This calls X's destructor only (since the type of the pointer was X*), Fix this by making X's destructor virtual
The Point: Always make the destructor virtual in classes that have subclasses, even if the destructor does not do anything!
Otherwise when we have a polymorphic variable with the type of the base class, it will not call the destructors of the subclasses
Final
If a class is not meant to have subclasses, declare it final
.
Last updated