Topic 3: Polymorphism and Overloading
Ever been in a singles bar?
A standard stimulus (message) provokes a unique response
Depending on the class¤
of the object you stimulate
This kind of behaviour¤
is called polymorphism.
The reason we can send a particular message to an object is because it
belongs to a class¤
for which that operation (receiving that message) is well-defined
Once a message is well-defined for a given class¤
it is automatically well-defined for any subclasses¤
However, we may wish to change (override) the way in which a specific
responds to a given message
If we are accessing an object via a pointer to its superclass¤,
that pointer could legitimately be pointing to an object of any
Can view polymorphism¤
as a form of abstraction¤
is an example of type enforcement: if an object is of type T it must respond
to a given message as a T would
is also an example of dynamic typing¤¤
because the actual type enforcement isn't done until the message is actually
sent (i.e. you don't know how the object will respond until you send the
Polymorphic (or Dynamic)
Normally in an OO program, when we specify that a message is to be sent
to an object the response is determined by the compiler (by looking at
the types of the objects and messages involved)
The compiler then translates that request into the equivalent assembler-level
This is called static dispatch
However, with polymorphism¤,
the code to dispatch¤
the message to the right handler (i.e. assembler subroutine) can't
be determined by the compiler
This is because the necessary information (namely the actual type of the
object) isn't available at compile time
Hence the compiler must instead insert code that will determine and invoke
the appropriate assembler subroutine at the point when the message is actually
This is called dynamic dispatch
can also apply to functions and operations
For example: what does a/b do?
An operation is overloaded if its behaviour¤
depends on the type of one or more of its arguments
Note that this is (usually) statically determined
Some languages (including C++) allow the programmer to define additional
overloadings for various operators
Another way to look at overloaded operators¤
is to treat (say) integer division and floating-point division as entirely
separate operations which just happen to have the same name
- Likewise we can envisage two or more functions with different behaviour¤
but the same name
For example: sizeof(), abs(), print(),
How can the compiler tell which overloaded function¤
How does it tell which overloaded operator¤
According to the types of the arguments provided
Hence functions and operators may have the same name but must have a unique
- Lippman & Lajoie
- Revision: Chapters 4 and 5.
- New: Sections 9.1 and 15.1.
- Revision: Chapter 6.
- New: Sections 7.4 to 7.7.
- Chapter 13
This material is part of the CSE2305 - Object-Oriented
Software Engineering course.
Copyright © Jon McCormack & Damian Conway, 1998-2005. All rights reserved.